content
stringlengths 7
1.05M
|
|---|
class GraphAlgos:
"""
Wrapper class which handle the graph algorithms
more efficiently, by abstracting repeating code.
"""
database = None # Static variable shared across objects.
def __init__(self, database, start, relationship, end = None, orientation = 'NATURAL', rel_weight = None):
# Initialize the static variable and class member.
if GraphAlgos.database is None:
GraphAlgos.database = database
# Initialize the optional parameter.
end = end if end is not None else start
# Construct the projection of the anonymous graph.
self.graph_projection = (
f'{{nodeProjection: ["{start}", "{end}"], '
'relationshipProjection: {'
f'{relationship}: {{'
f'type: "{relationship}", '
f'orientation: "{orientation}"'
)
# If the relationship weight property exists, then set it.
if rel_weight is not None:
self.graph_projection += f', properties: "{rel_weight}"'
# Add two right brackets to complete the query.
self.graph_projection += '}}'
def pagerank(self, write_property, max_iterations = 20, damping_factor = 0.85):
setup = (f'{self.graph_projection}, '
f'writeProperty: "{write_property}", '
f'maxIterations: {max_iterations}, '
f'dampingFactor: {damping_factor}}}'
)
GraphAlgos.database.execute(f'CALL gds.pageRank.write({setup})', 'w')
def nodeSimilarity(self, write_property, write_relationship, cutoff = 0.5, top_k = 10):
setup = (f'{self.graph_projection}, '
f'writeProperty: "{write_property}", '
f'writeRelationshipType: "{write_relationship}", '
f'similarityCutoff: {cutoff}, '
f'topK: {top_k}}}'
)
GraphAlgos.database.execute(f'CALL gds.nodeSimilarity.write({setup})', 'w')
def louvain(self, write_property, max_levels = 10, max_iterations = 10):
setup = (f'{self.graph_projection}, '
f'writeProperty: "{write_property}", '
f'maxLevels: {max_levels}, '
f'maxIterations: {max_iterations}}}'
)
GraphAlgos.database.execute(f'CALL gds.louvain.write({setup})', 'w')
# These methods enable the use of this class in a with statement.
def __enter__(self):
return self
# Automatic cleanup of the created graph of this class.
def __exit__(self, exc_type, exc_value, tb):
if exc_type is not None:
traceback.print_exception(exc_type, exc_value, tb)
|
total = int(input())
b_num = 0
b_x = 0
b_y = 0
for i in range(total):
num, x, y = map(int, input().split())
mn = num - b_num
mx = abs(x - b_x)
my = abs(y - b_y)
if mn < mx + my:
print("No")
exit()
else:
if b_num % 2 == (mx + my) % 2:
mn = num
b_x = x
b_y = y
else:
# print("{} {} {}".format(b_num, mx, my))
print("No")
exit()
print("Yes")
|
strMD5Salt = "vfkpbin1ix2rb88gfjebs0f60cbvhedl"
dictURL = {
"search/ershoufang": {
"URL": "https://ajax.lianjia.com/map/search/ershoufang/?city_id={city_id}&group_type={group_type}&"
"max_lat={max_lat}&min_lat={min_lat}&max_lng={max_lng}&min_lng={min_lng}&"
"filters=%7B%7D&request_ts={request_ts}&source=ljpc&authorization={authorization}",
"MD5Data": strMD5Salt + "city_id={city_id}group_type={group_type}max_lat={max_lat}"
"max_lng={max_lng}min_lat={min_lat}min_lng={min_lng}request_ts={request_ts}"
},
"subway/station": {
"URL": "https://ajax.lianjia.com/map/subway/station/?city_id={city_id}&line_id={line_id}&"
"request_ts={request_ts}&source=ljpc&authorization={authorization}",
"MD5Data": strMD5Salt + "city_id={city_id}line_id={line_id}request_ts={request_ts}"
},
"subway/line": {
"URL": "https://ajax.lianjia.com/map/subway/line/?city_id={city_id}&request_ts={request_ts}&source=ljpc"
"&authorization={authorization}",
"MD5Data": strMD5Salt + "city_id={city_id}request_ts={request_ts}"
},
"resblock/ershoufangcard": {
"URL": "https://ajax.lianjia.com/map/resblock/ershoufangcard/?id={id}&request_ts={request_ts}&"
"source=ljpc&authorization={authorization}",
"MD5Data": strMD5Salt + "id={id}request_ts={request_ts}"
},
"resblock/ershoufanglist": {
"URL": "https://ajax.lianjia.com/map/resblock/ershoufanglist/?id={id}&order={order}&page={page}&"
"filters=%7B%7D&request_ts={request_ts}&source=ljpc&authorization={authorization}",
"MD5Data": strMD5Salt + "id={id}order={order}page={page}request_ts={request_ts}"
},
}
dictCity = {
'珠海': {'city_url': 'https://zh.lianjia.com/',
'city_id': 440400,
'max_lat': 22.256915,
'max_lng': 113.562447,
'min_lat': 21.956915,
'min_lng': 113.262447},
'长沙': {'city_url': 'https://cs.lianjia.com/',
'city_id': 430100,
'max_lat': 28.213478,
'max_lng': 112.979353,
'min_lat': 27.913478,
'min_lng': 112.679353},
'深圳': {'city_url': 'https://sz.lianjia.com/',
'city_id': 440300,
'max_lat': 22.546054,
'max_lng': 114.025974,
'min_lat': 22.246054,
'min_lng': 113.725974},
'重庆': {'city_url': 'https://cq.lianjia.com/',
'city_id': 500000,
'max_lat': 29.544606,
'max_lng': 106.530635,
'min_lat': 29.244606,
'min_lng': 106.230635},
'苏州': {'city_url': 'https://su.lianjia.com/',
'city_id': 320500,
'max_lat': 31.317987,
'max_lng': 120.619907,
'min_lat': 31.017987,
'min_lng': 120.319907},
'西安': {'city_url': 'https://xa.lianjia.com/',
'city_id': 610100,
'max_lat': 34.2778,
'max_lng': 108.953098,
'min_lat': 33.9778,
'min_lng': 108.653098},
'廊坊': {'city_url': 'https://lf.lianjia.com/',
'city_id': 131000,
'max_lat': 39.518611,
'max_lng': 116.703602,
'min_lat': 39.218611,
'min_lng': 116.403602},
'北京': {'city_url': 'https://bj.lianjia.com/',
'city_id': 110000,
'max_lat': 39.929986,
'max_lng': 116.395645,
'min_lat': 39.629986,
'min_lng': 116.095645},
'济南': {'city_url': 'https://jn.lianjia.com/',
'city_id': 370100,
'max_lat': 36.682785,
'max_lng': 117.024967,
'min_lat': 36.382785,
'min_lng': 116.724967},
'郑州': {'city_url': 'https://zz.lianjia.com/',
'city_id': 410100,
'max_lat': 34.75661,
'max_lng': 113.649644,
'min_lat': 34.45661,
'min_lng': 113.349644},
'天津': {'city_url': 'https://tj.lianjia.com/',
'city_id': 120000,
'max_lat': 39.14393,
'max_lng': 117.210813,
'min_lat': 38.84393,
'min_lng': 116.910813},
'厦门': {'city_url': 'https://xm.lianjia.com/',
'city_id': 350200,
'max_lat': 24.489231,
'max_lng': 118.103886,
'min_lat': 24.189231,
'min_lng': 117.803886},
'成都': {'city_url': 'https://cd.lianjia.com/',
'city_id': 510100,
'max_lat': 30.679943,
'max_lng': 104.067923,
'min_lat': 30.379943,
'min_lng': 103.767923},
'沈阳': {'city_url': 'https://sy.lianjia.com/',
'city_id': 210100,
'max_lat': 41.808645,
'max_lng': 123.432791,
'min_lat': 41.508645,
'min_lng': 123.132791},
'大连': {'city_url': 'https://dl.lianjia.com/',
'city_id': 210200,
'max_lat': 38.94871,
'max_lng': 121.593478,
'min_lat': 38.64871,
'min_lng': 121.293478},
'上海': {'city_url': 'https://sh.lianjia.com/',
'city_id': 310000,
'max_lat': 31.249162,
'max_lng': 121.487899,
'min_lat': 30.949162,
'min_lng': 121.187899},
'石家庄': {'city_url': 'https://sjz.lianjia.com/',
'city_id': 130100,
'max_lat': 38.048958,
'max_lng': 114.522082,
'min_lat': 37.748958,
'min_lng': 114.222082},
'南京': {'city_url': 'https://nj.lianjia.com/',
'city_id': 320100,
'max_lat': 32.057236,
'max_lng': 118.778074,
'min_lat': 31.757236,
'min_lng': 118.478074},
'青岛': {'city_url': 'https://qd.lianjia.com/',
'city_id': 370200,
'max_lat': 36.105215,
'max_lng': 120.384428,
'min_lat': 35.805215,
'min_lng': 120.084428},
'广州': {'city_url': 'https://gz.lianjia.com/',
'city_id': 440100,
'max_lat': 23.120049,
'max_lng': 113.30765,
'min_lat': 22.820049,
'min_lng': 113.00765},
'佛山': {'city_url': 'https://fs.lianjia.com/',
'city_id': 440600,
'max_lat': 23.035095,
'max_lng': 113.134026,
'min_lat': 22.735095,
'min_lng': 112.834026},
'武汉': {'city_url': 'https://wh.lianjia.com/',
'city_id': 420100,
'max_lat': 30.581084,
'max_lng': 114.3162,
'min_lat': 30.281084,
'min_lng': 114.0162},
'海口': {'city_url': 'https://hk.lianjia.com/',
'city_id': 460100,
'max_lat': 20.022071,
'max_lng': 110.330802,
'min_lat': 19.722071,
'min_lng': 110.030802},
'烟台': {'city_url': 'https://yt.lianjia.com/',
'city_id': 370600,
'max_lat': 37.536562,
'max_lng': 121.309555,
'min_lat': 37.236562,
'min_lng': 121.009555},
'中山': {'city_url': 'https://zs.lianjia.com/',
'city_id': 442000,
'max_lat': 22.545178,
'max_lng': 113.42206,
'min_lat': 22.245178,
'min_lng': 113.12206},
'无锡': {'city_url': 'https://wx.lianjia.com/',
'city_id': 320200,
'max_lat': 31.570037,
'max_lng': 120.305456,
'min_lat': 31.270037,
'min_lng': 120.005456},
'惠州': {'city_url': 'https://hui.lianjia.com/',
'city_id': 441300,
'max_lat': 23.11354,
'max_lng': 114.410658,
'min_lat': 22.81354,
'min_lng': 114.110658},
'东莞': {'city_url': 'https://dg.lianjia.com/',
'city_id': 441900,
'max_lat': 23.043024,
'max_lng': 113.763434,
'min_lat': 22.743024,
'min_lng': 113.463434},
'杭州': {'city_url': 'https://hz.lianjia.com/',
'city_id': 330100,
'max_lat': 30.259244,
'max_lng': 120.219375,
'min_lat': 29.959244,
'min_lng': 119.919375},
'合肥': {'city_url': 'https://hf.lianjia.com/',
'city_id': 340100,
'max_lat': 31.866942,
'max_lng': 117.282699,
'min_lat': 31.566942,
'min_lng': 116.982699}}
dictGroupType = {
"district": 0.3, # 行政区
"bizcircle": 0.08, # 商圈
"community": 0.01 # 居民小区
}
|
# uninhm
# https://atcoder.jp/contests/abc164/tasks/abc164_c
# dictionary
a = {}
ans = 0
n = int(input())
for _ in range(n):
i = input()
ans += a.get(i, 1)
a[i] = 0
print(ans)
|
class UnionFind:
def __init__(self, size):
self.parent = list(range(size))
self.component = [[i] for i in range(size)]
def root(self, i):
if self.parent[i] != i:
self.parent[i] = self.root(self.parent[i])
return self.parent[i]
def unite(self, i, j):
i, j = self.root(i), self.root(j)
if len(self.component[i]) < len(self.component[j]):
i, j = j, i
self.parent[j] = i
self.component[i] += self.component[j]
|
class Print:
"""
A simple text-printing component
"""
def doPrint(self, v):
print(v)
@staticmethod
def cfgr(builder):
## outputs
builder.addInput('on').string_to_method(lambda obj: obj.doPrint)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TClassStatic(object):
obj_num = 0
def __init__(self, data):
self.data = data
TClassStatic.obj_num += 1
def printself(self):
print("self.data: ", self.data)
@staticmethod
def smethod():
print("the number of obj is : ", TClassStatic.obj_num)
@classmethod
def cmethod(cls):
print("cmethod : ", cls.obj_num)
print(';first')
cls.smethod()
print('last')
def main():
objA = TClassStatic(10)
objB = TClassStatic(12)
objA.printself()
objB.printself()
objA.smethod()
objB.cmethod()
print("------------------------------")
TClassStatic.smethod()
TClassStatic.cmethod()
if __name__ == "__main__":
main()
|
# This code is connected with '18 - Modules.py'
def kgs_to_lbs(weight):
return 2.20462 * weight
def lbs_t_kgs(weight):
return 0.453592 * weight
|
"""December 1st"""
def sevenish_number(num):
"""Sevenish Number"""
power_of_two = 0
sevenish = 0
while num > 0:
val = pow(7, power_of_two) if num % 2 == 1 else 0
sevenish += val
power_of_two += 1
num //= 2
return sevenish
|
"""
------------------------------------------------------------------------------
@file variable.py
@author Milos Milicevic (milosh.mkv@gmail.com)
@brief ...
@version 0.1
@date 2020-08-26
@copyright Copyright (c) 2020
Distributed under the MIT software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
------------------------------------------------------------------------------
"""
class Variable(object):
def __init__(self):
""" Constructs variable object. """
self.name = None # Variable name (identifier)
self.type = None # Variable type (int, char, boolean, anyClassName)
self.kind = None # Variable kind (field, static, local, argument)
self.id = None # Variable id (id of certain kind)
def __str__(self):
""" Returns string representaion of object. """
return "Name => {0}; Type => {1}; Kind => {2}; Id => {3};".format(self.name, self.type, self.kind, self.id)
|
n=int(input())
arr=[]
game=True
for i in range(n):
arr.append((input()))
for j in range(n):
if "OO" in arr[j]:
print("YES")
ind=arr[j].index("OO")
if ind==0 and arr[j][ind+1]=="O":
arr[j]="++|"+arr[j][3]+arr[j][4]
if ind==3 and arr[j][ind+1]=="O":
arr[j]=arr[j][0]+arr[j][1]+"|"+"++"
game=False
break
if game==True:
print('NO')
else:
for k in range(n):
print(arr[k])
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 03:30:25 2021
@author: Septhiono
"""
year=int(input("Which year would you like to check?"))
if year%4==0:
if year%100==0:
if year%400==0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
|
"""
LeetCode Problem: 1095. Find in Mountain Array
Link: https://leetcode.com/problems/find-in-mountain-array/
Language: Python
Written by: Mostofa Adib Shakib
"""
class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
#binary search to find the peak mountain
high = mountain_arr.length() -1
low = 0
while(low<high):
mid = (low+high)//2
if mountain_arr.get(mid) > mountain_arr.get(mid+1):
high = mid
else:
low = mid+1
peak = low
#binary search to find target in the acsending part of the array
low = 0
high = peak+1
while(low<high):
mid = (low+high)//2
temp = mountain_arr.get(mid)
if target==temp: return mid
if temp>target:
high = mid
else:
low = mid+1
#binary search to find target in the descending part of the array
low = peak+1
high = mountain_arr.length()
while(low<high):
mid = (low+high)//2
temp = mountain_arr.get(mid)
if target==temp: return mid
if temp<target:
high = mid
else:
low = mid+1
return -1 # returns -1 if target not found in the mountain array
|
"""Modules for user interfaces.
Modules:
ui -- Provide a base class for user interface facades.
ui_cmd -- Provide a facade for a command line user interface.
ui_tk -- Provide a facade for a Tkinter based GUI.
ui_mb -- Provide a facade for a GUI featuring just message boxes.
"""
|
class A:
def spam(self):
print('A.spam')
class B(A):
def spam(self):
print('B.spam')
super().spam() # Call parent spam()
class C:
def __init__(self):
self.x = 0
class D(C):
def __init__(self):
super().__init__()
self.y = 1
d = D()
print(d.y)
class Base:
def __init__(self):
print('Base.__init__')
class A(Base):
def __init__(self):
Base.__init__(self)
print('A.__init__')
|
foo = [25, 68, 'bar', 89.45, 789, 'spam', 0, 'last item']
print(foo[0], ' FIRST ITEM')
print(foo[len(foo) - 1], ' LAST ITEM')
|
# Copyright 2017 Citrix Systems
#
# 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 set_host_enabled(session, enabled):
args = {"enabled": enabled}
return session.call_plugin('xenhost.py', 'set_host_enabled', args)
def get_host_uptime(session):
return session.call_plugin('xenhost.py', 'host_uptime', {})
def get_host_data(session):
return session.call_plugin('xenhost.py', 'host_data', {})
def get_pci_type(session, pci_device):
return session.call_plugin_serialized('xenhost.py', 'get_pci_type',
pci_device)
def get_pci_device_details(session):
return session.call_plugin_serialized('xenhost.py',
'get_pci_device_details')
|
"""
Напишите программу, которая приветствует пользователя, выводя слово Hello, введенное имя и знаки препинания по образцу.
Программа должна считывать в строковую переменную значение и писать соответствующее приветствие.
Обратите внимание, что после запятой должен обязательно стоять пробел, а перед восклицательным знаком пробела нет.
Операцией конкатенации строк (+) пользоваться нельзя.
"""
greeting = input()
print('Hello,', greeting, end='')
print('!')
|
"""
get information of receptive field
"""
def get_receptive_field(neuron_index, layer_info, pad=(0, 0)):
"""
neuron_index: tuple of length 2 or int represented x axis and y
layer_info: tuple of length 4 has information of receptive_field
"""
n, j, rf, start = layer_info
if isinstance(neuron_index, tuple):
center_y = start + (neuron_index[1]) * (j)
center_x = start + (neuron_index[0]) * (j)
else:
center_y = start + (neuron_index // n) * (j)
center_x = start + (neuron_index % n) * (j)
return (center_x, center_y), (rf / 2, rf / 2)
|
"""This module regroups all exceptions tied to pyqtcli cli."""
class QresourceError(Exception):
"""Exception raised with problems concerning qresource node in qrc files."""
def __init__(self, arg):
super(QresourceError, self).__init__()
self.msg = arg
def __str__(self):
return self.msg
class PyqtcliConfigError(Exception):
"""Exception raised with problems concerning .pyqtclirc config file."""
def __init__(self, arg):
super(PyqtcliConfigError, self).__init__()
self.msg = arg
def __str__(self):
return self.msg
class QRCFileError(Exception):
"""Exception raised with problems concerning qrc files."""
def __init__(self, arg):
super(QRCFileError, self).__init__()
self.msg = arg
def __str__(self):
return self.msg
|
valores = input().split()
valores = list(map(int,valores))
h1, h2 = valores
if(h1 == h2):
print('O JOGO DUROU %d HORA(S)' %24)
else:
if(h2 < h1):
print('O JOGO DUROU %d HORA(S)' %((24 - h1) + h2))
else:
print('O JOGO DUROU %d HORA(S)' %(h2 - h1))
|
#1부터 100까지 3의 배수의 합계
# 클래스 선언부(객체지양 : 향후 코드 분석)
#함수 선언부
# (전역)변수 선언부 (초기화)
start,end,hap = [0] *3
#a,b=[],[]
#메인 코드부
if __name__=='__main__' :
for i in range(1,101) :
if i % 3 ==0:
hap += i
else:
pass
# 같은 내용
# for i in range(1,101) :
# if i % 3 !==0:
# pass
# else:
# hap += i
print(hap)
|
def WriteOBJ(filename, vertrices, vts, vns, facesV, facesVt, facesVn):
f=file(filename,"w+")
for vertex in vertrices:
f.write("v ")
for i in range(len(vertex)):
f.write(str(vertex[i]))
f.write(" ")
f.write("\n")
if len(vts) != 0:
for vt in vts:
f.write("vt ")
for i in range(len(vt)):
f.write(str(vt[i]))
f.write(" ")
f.write("\n")
if len(vns) != 0:
for vn in vns:
f.write("vn ")
for i in range(len(vn)):
f.write(str(vn[i]))
f.write(" ")
f.write("\n")
if len(vts) != 0 and len(vns) != 0:
for (faceV, faceVt, faceVn) in zip(facesV, facesVt, facesVn):
f.write("f ")
for i in range(len(faceV)):
f.write(str(faceV[i]))
f.write("/")
f.write(str(faceVt[i]))
f.write("/")
f.write(str(faceVn[i]))
f.write(" ")
f.write("\n")
if len(vts) != 0 and len(vns) == 0:
for (faceV, faceVt) in zip(facesV, facesVt):
f.write("f ")
for i in range(len(faceV)):
f.write(str(faceV[i]))
f.write("/")
f.write(str(faceVt[i]))
f.write(" ")
f.write("\n")
if len(vts) == 0 and len(vns) == 0:
for faceV in facesV:
f.write("f ")
for i in range(len(faceV)):
f.write(str(faceV[i]))
f.write(" ")
f.write("\n")
f.close
|
num1=10
num2=20
num3=30
num4=40
num5=50
num6=60
nihaoma=weijialan
|
#! Простые задачки.
# 1. Даны два целых числа, отличных от нуля. Найдите их сумму,
# произведение, разность, частное.
def test_1(a, b):
if str(a).isdigit() and str(b).isdigit():
return a + b, a * b, a - b, a / b
return "Error"
print(test_1(1, 4))
# 2. Поменяйте местами значения двух переменных.
def test_2(a, b):
a, b = b, a
return a, b
print(test_2(True, False))
# 3. Дано трехзначное число. Найдите произведение их цифр.
def test_3(a):
b = 1
if 99 < a < 1000:
for num in str(a):
b *= int(num)
return b
return "Error"
print(test_3(222))
# 4. Дано пятизначное число. Найдите разность двух чисел. Первое
# число равно сумме цифр исходного числа, стоящих на четных местах.
# Второе число равно сумме цифр, стоящих на нечетных местах.
def test_4(a):
if 9999 < a < 100000:
return (int(list(str(a))[1]) + int(list(str(a))[3]) -
int(list(str(a))[0]) - int(list(str(a))[2]) -
int(list(str(a))[4]))
return "Error"
print(test_4(12345))
# 5.
|
"""
EXERCÍCIO 056: Analisador Completo
Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre:
- A média de idade do grupo.
- Qual é o nome do homem mais velho.
- Quantas mulheres têm menos de 20 anos.
"""
continuar = True
while continuar:
pessoas = []
soma = 0
cont = 0
maior = 0
for c in range (1,5):
print('-'*5, f'{c}ª PESSOA', '-'*5 )
nome = str(input('Nome: '))
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: ')).upper()
pessoas.append({ 'Nome': nome, 'Idade': idade, 'Sexo [M/F]': sexo })
soma += idade
média = soma/4
if idade < 20 and sexo == 'F':
cont += 1
elif idade > maior and sexo == 'M':
maior = idade
nomeM = nome
print(f'A média de idade do grupo é de {média:.2f} anos. ')
print(f'O homem mais velho tem {maior} anos e se chama {nomeM}. ')
print(f'Ao todo são(é) {cont} mulher(es) com menos de 20 anos. ')
n = str(input('Deseja continuar? [S/N]')).upper()
if n == 'N':
print('Muito obrigado, volte sempre.')
continuar = False
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__project__ = 'leetcode'
__file__ = '__init__.py'
__author__ = 'king'
__time__ = '2020/2/22 20:37'
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
佛祖保佑 永无BUG
"""
def neighbors(cur):
return []
def DFS(root, target):
visited = set()
# add root to stack
stack = [root]
while stack:
cur = stack.pop()
if cur == target:
return True
for node in neighbors(cur):
if node not in visited:
stack.append(node)
visited.add(node)
return False
|
while True:
try:
chars = input()
# nums = int(chars)
level0 = ['zero']
level1 = ['','one','two','three','four','five','six', 'seven',' eight','nine', 'ten']
level1_1= ['','eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixten', 'seventeen', 'eighteen', 'nineteen']
level2 = ['','','twenty','thirty', 'forty', 'fifty','sixty',' seventy', 'eighty', 'ninety']
high = ['','thousand','million','billion']
levelAnd = ['and']
def threeNumTran(num3):
if len(num3) == 0:
return ''
out = []
length = len(num3)
one = int(num3[-1])
two = int(num3[-2]) if length >1 else 0
three = int(num3[-3]) if length >2 else 0
if two == 1:
out.append(level1_1[one])
else:
out.extend([level2[two] ,level1[one]])
if three != 0:
out = [level1[three] , 'hundred' , 'and'] + out
# print(out)
return ' '.join([x for x in out if len(x)!=0])
# def high2Val(numThousand):
# n = int(num123
# Thousand // 3)
# left = numThousand % 3
# return [high[left]] + ['billion' for _ in range(n)]
def pos2Unit(pos):
# assert pos % 3 == 0
numThousand = int( (pos-1) // 3)
n = int(numThousand // 3)
left = numThousand % 3
r = [high[left]] + ['billion' for _ in range(n)]
r = [x for x in r if len(x)!=0]
return ' '.join(r)
def pos2Unit_dfs(pos):
if pos < 3:
if pos == 0:
return []
if pos == 1:
return ['thousand']
if pos == 2:
return ['million']
return pos2Unit_dfs(pos-3) + ['billion']
length = len(chars)
parts = []
units = []
for i in range(length, -1,-3):
ed = i
st = i-3 if i-3>0 else 0
num3 = chars[st:ed]
if len(num3) != 0:
part = threeNumTran(num3)
pos = length - st
unit = pos2Unit(pos)
parts.append(part)
units.append(unit)
res = []
for k,v in zip(parts, units):
# print(k,v)
# if len(k)!=0:
# r = [k,v]
res.append(' '.join([k,v]))
output = ' '.join(reversed(res))
print(output)
except :
break
|
'''Geração de HTML'''
arquivo = open('ola.html','w',encoding='utf-8')
arquivo.write('''<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<title>Titulo da pagina</title>
</head>
<body>
Olá!!!
</body>
</html>''')
arquivo.close()
|
items = [2, 25, 9]
divisor = 12
for item in items:
if item%divisor == 0:
found = item
break
else: # nobreak
items.append(divisor)
found = divisor
print("{items} contains {found} which is a multiple of {divisor}"
.format(**locals()))
|
class Solution:
def hIndex(self, citations):
n = len(citations)
at_least = [0] * (n + 2)
for c in citations:
at_least[min(c, n + 1)] += 1
for i in xrange(n, -1, -1):
at_least[i] += at_least[i + 1]
for i in xrange(n, -1, -1):
if at_least[i] >= i:
return i
|
class ColumnRef:
table = ''
column = ''
cascade_row = None
def __init__(self, table, column, cascade_row=True):
# cascade_row=True means that row in table should be removed
# if value in column that owns reference is not found.
# i.e, reference from stop_times.stop_id to stops.stop_id has cascade_row=True,
# since stops should be pruned if not used in trips, and same for the reverse. But a
# reference from stops.stop_id to stops.parent_station has cascade_row=False
self.table = table
self.column = column
self.cascade_row = cascade_row
|
"""
Author: Cameron Tee
A class keeping track of the game stats.
Only one life in Flappy Bird.
This class controls the game state (whether playing or not).
"""
class GameStats():
def __init__(self, settings):
"""
Initialise the gamestats object.
"""
self.settings = settings
self.reset_stats()
#Begin the game in an inactive state
self.game_active = False
#Hiscore should never be reset
self.hiscore = 0
def reset_stats(self):
"""
Score and the single life are reset between attempts
"""
self.lives_left = self.settings.lives
self.score = 0
|
'''
URL: https://leetcode.com/problems/move-zeroes/
Difficulty: Easy
Title: Move Zeroes
'''
################### Code ###################
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zeroCount = 0
i = 0
while i < len(nums):
if nums[i] == 0:
nums.pop(i)
zeroCount += 1
else:
i += 1
nums.extend([0] * zeroCount)
|
numbers = [1,2,3,4,5,6,7,11]
res = 0
for num in numbers:
res = res + num
print("with sum: ",sum(numbers))
print("without sum: ",res)
|
def remove_duplicates(S: str) -> str:
r = S[0]
for i in range(1, len(S)):
if len(r) == 0:
r += S[i]
else:
if r[-1] == S[i]:
if len(r) == 1:
r = ''
else:
r = r[:-1]
else:
r += S[i]
return r
|
f1, f2 = map(float, input().split())
flutuacao = 1.0 * (1.0 + f1/100) * (1 + f2/100)
print("%.6f" % ((flutuacao - 1.0)*100))
|
class Primes:
def __init__(self, first, last=None):
self.curr = None
if last is None:
self.first = 2
self.last = first
else:
self.first = first
self.last = last
def __iter__(self):
return self
def __next__(self):
if self.curr is None:
self.curr = 2
return self.curr
while self.curr < self.last:
self.curr += 1
if Primes.__prime(self.curr):
return self.curr
raise StopIteration()
def __prime(n):
for d in range(2, n):
if n % d == 0:
return False
return True
for p in Primes(100):
print(p)
|
# coding: iso-8859-1 -*-
repete = 'sim'
while repete == 'sim':
frase = str(input('Digite uma frase para saber se é palindroma: ')).upper().strip()
separa = frase.split()
junto= ''.join(separa)
reverso =''
for letra in range(len(junto)-1,-1,-1):
reverso += junto[letra]
if reverso == junto:
print(f'A frase {frase} é palindroma pois sem os espaços fica: {junto} sendo igual ao ler de trás pra frente: {reverso}')
else:
print(f'A frase {frase} não é palindroma pois sem os espaços fica: {junto} sendo diferente de ao ler de trás pra frente: {reverso}')
repete = input ('Avaliar outra frase? Digite sim ou não: \n').lower ( )
while repete != 'sim' and repete != 'não':
repete = input('Opção inválida ? Digite sim ou não: \n').lower()
print('Até a próxima!')
|
a, b = map(int, input().split())
while a != 0 and b != 0:
if a > 0 and b > 0:
print("primeiro")
elif a < 0 < b:
print("segundo")
elif a < 0 and b < 0:
print("terceiro")
elif a > 0 > b:
print("quarto")
a, b = map(int, input().split())
|
# https://github.com/michal037
class Singleton:
def __new__(cls, *_, **__):
self = object.__new__(cls)
cls.__new__ = lambda *a, **b: self
return self
def singleton(self):
self.__class__.__new__ = lambda *c, **d: self
### EXAMPLE 1 ### EXAMPLE 1 ### EXAMPLE 1 ### EXAMPLE 1 ### EXAMPLE 1 ##########
class MyClass(Singleton):
def __init__(self, a, *args, **kwargs):
self.val = a
print(f'a = {a}')
for arg in args:
print(f'next arg = {arg}')
for key, value in kwargs.items():
print(f'{key} = {value}')
print()
a = MyClass(1, 2, 3, hi='hello', it='works')
b = MyClass(4, 5, 6, cc='hello', dd='works')
# Proof that it's the same object.
print(f'{{a.val, b.val}} = {{{a.val}, {b.val}}}') # {4, 4}
print(f'(a is b) = {a is b}') # True
print()
### EXAMPLE 2 ### EXAMPLE 2 ### EXAMPLE 2 ### EXAMPLE 2 ### EXAMPLE 2 ##########
class Test(Singleton):
# Assuming that we are overriding the __new__ magic method,
# we have to manually trigger .singleton() method.
def __new__(cls):
self = object.__new__(cls)
self.value = 'hi'
return self
t1 = Test()
t2 = Test()
print(f'(t1 is t2) = {t1 is t2}') # False
t2.singleton()
# From now, the constructor always returns reference to the same object.
t3 = Test()
print(f'(t2 is t3) = {t2 is t3}') # True
|
"""
Write a function, connected_components_count, that takes in the adjacency list of an undirected graph.
The function should return the number of connected components within the graph.
depth first
n = number of nodes
e = number edges
Time: O(e)
Space: O(n)
"""
def count(graph):
visited = set()
count = 0
for node in graph:
if explore(graph, node, visited) == True:
count += 1
return count
def explore(graph, current, visited):
if current in visited:
return False
visited.add(current)
for neighbor in graph[current]:
explore(graph, neighbor, visited)
return True
|
class TriggerPool:
def __init__(self):
self.triggers = [] # Trigger list
self.results = [] # Result list
def add(self, trigger):
"""add one trigger to the pool"""
self.triggers.append(trigger)
def test(self, model, data):
"""test untested triggers"""
untested_triggers = range(len(self.results), len(self.triggers))
for i in untested_triggers:
self.results.append(model.test(data, 0.1, self.triggers[i]))
def expand(self, num=1):
"""add new triggers based on self-expansion rules"""
scores = [result.accuracy() for result in self.results] # TODO: add density punishment
best_trigger = self.triggers[scores.index(max(scores))]
def spawn(trigger):
return trigger.duplicate().add_noise(type_="Gaussian",args={"std":0.1})
for i in range(num):
self.add(spawn(best_trigger))
def success_triggers(self, threshold=90):
"""threshold 0~100. return a list of triggers"""
return [self.triggers[i]
for i in range(len(self.results))
if self.results[i].accuracy() >= threshold]
|
def climbStairs(n: int) -> int:
stairs = [1, 1]
for i in range(2, n + 1):
stairs.append(stairs[-1] + stairs[-2])
return stairs[n]
|
text=input('Enter and check if your input is a palindrome or not: ')
ltext=text.lower()
rtext="".join((reversed(ltext)))
if rtext==ltext:
print('Your input is a palindrome.')
else:
print('Your input is not a palindrome.')
|
"""
Running Successfully
import unittest
import math
from PIL import Image
from SyntheticDataset2.ImageCreator.specified_target_with_background import SpecifiedTargetWithBackground
class SpecifiedTargetWithBackgroundTestCase(unittest.TestCase):
def setUp(self):
self.path_to_background = "tests/images/competition_grass_1.JPG"
self.test_image1 = SpecifiedTargetWithBackground("circle", "?", "A", (255, 255, 255, 255), (255, 0, 0, 255), 0).create_specified_target_with_background()
self.test_image2 = SpecifiedTargetWithBackground("semicircle", "E", "E", (0, 255, 0, 255), (0, 0, 255, 255), 45).create_specified_target_with_background()
self.test_image3 = SpecifiedTargetWithBackground("cross", "D", "I", (255, 255, 0, 255), (255, 0, 255, 255), 90).create_specified_target_with_background()
self.test_image4 = SpecifiedTargetWithBackground("heptagon", "S", "O", (0, 255, 255, 255), (0, 0, 0, 255), 135).create_specified_target_with_background()
self.test_image5 = SpecifiedTargetWithBackground("star", "N", "U", (66, 66, 66, 255), (233, 233, 233, 255), 180).create_specified_target_with_background()
'''
Settings:
PPSI = 10
SINGLE_TARGET_SIZE_IN_INCHES = 24
SINGLE_TARGET_PROPORTIONALITY = 2.5
PIXELIZATION_LEVEL = 0
NOISE_LEVEL = 0
'''
def test_create_specified_target_with_specified_background(self):
self.assertTrue(abs(max(self.test_image1.width, self.test_image1.height) - 260) < 3)
self.assertTrue(self.test_image1.load()[self.test_image1.width/2, self.test_image1.height/2] == (255, 255, 255))
self.assertTrue(abs(max(self.test_image2.width, self.test_image2.height) - 260) < 3)
self.assertTrue(self.test_image2.load()[self.test_image2.width/2, self.test_image2.height/2] == (0, 255, 0))
self.assertTrue(abs(max(self.test_image2.width, self.test_image2.height) - 260) < 3)
self.assertTrue(self.test_image3.load()[self.test_image3.width/2, self.test_image3.height/2] == (255, 0, 255))
self.assertTrue(abs(max(self.test_image2.width, self.test_image2.height) - 260) < 3)
self.assertTrue(self.test_image4.load()[self.test_image4.width/2, self.test_image4.height/2] == (0, 255, 255))
self.assertTrue(abs(max(self.test_image2.width, self.test_image2.height) - 260) < 3)
self.assertTrue(self.test_image5.load()[self.test_image5.width/2, self.test_image5.height/2] == (66, 66, 66))
"""
|
def kmp(s):
p = [-1]
k = -1
for c in s:
while k >= 0 and s[k] != c:
k = p[k]
k += 1
p.append(k)
return p
def period(s):
k = len(s) - kmp(s)[-1]
if len(s) % k == 0:
return k
return len(s)
s = input()
m = int(input())
p = period(s)
print(m // p % (10**9 + 7))
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def split(self, head):
slow = head
fast = head
slow_pre = head
while fast and fast.next:
slow_pre = slow
slow, fast = slow.next, fast.next.next
slow_pre.next = None
return head, slow
def merge(self, p1, p2):
if not p2:
return p1
if not p1:
return p2
head = ListNode()
p = head
while p1 and p2:
if p1.val < p2.val:
p.next = ListNode(p1.val)
p = p.next
p1 = p1.next
else:
p.next = ListNode(p2.val)
p = p.next
p2 = p2.next
if p1:
p.next = p1
elif p2:
p.next = p2
return head.next
def mergeSort(self, head):
if not head or not head.next:
return head
p1, p2 = self.split(head)
p1 = self.mergeSort(p1)
p2 = self.mergeSort(p2)
head = self.merge(p1, p2)
return head
def sortList(self, head: ListNode) -> ListNode:
return self.mergeSort(head)
|
#!/usr/bin/python3
"""
插入排序
insert + sort
"""
def insert_sort(ds):
for i in range(1, len(ds)):
key = ds[i]
j = i - 1
while j >= 0 and key < ds[j]:
ds[j + 1] = ds[j]
j -= 1
ds[j + 1] = key
random_wait_sort = [12, 34, 32, 24, 28, 39, 5,
22, 11, 25, 33, 32, 1, 25, 3, 8, 7, 1, 34, 7]
insert_sort(random_wait_sort)
print(random_wait_sort)
|
"""
File: circulararray.py
Author: Brian Atwell
Date: August 21, 2018
Descrioption: This a python implementation of a circular array using a list.
This implementation could be used as a queue or an array.
Copyright (c) 2018, Brian Atwell
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by the Brian Atwell.
4. Neither Brian Atwell nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Brian Atwell ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Brian Atwell BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
class CircularArray:
def __init__(self, size):
self.array = []
self.size = size
self.startPos=0
self.count=0
def __getitem__(self, key):
if key >= self.size:
return None
pos=(self.startPos+key)%self.size
return self.array[pos]
def __setitem__(self, idx, value):
if idx > self.size:
return
if idx > (self.count+1) or self.count >= self.size:
return
if idx == (self.count+1):
count+=1
pos=(self.startPos+idx)%self.size
self.array[pos] = value
def __len__(self):
return self.count
def append(self, obj):
if (self.count) >= self.size:
return
self.count+=1
if len(self.array) < self.count or len(self.array) < self.size:
self.array.append(obj)
else:
pos=(self.startPos+self.count-1)%self.size
self.array[pos]=obj
def clear(self):
self.startPos=0
self.endPos=0
#def copy(self):
def generator(self):
idx = 0
pos=self.startPos
while idx < self.count:
yield self.array[pos]
pos=(pos+1)%self.size
idx+=1
#def extend(self):
def index(self, value):
pos = 0
for obj in self.generator():
if obj == value:
return pos
pos+=1
def insert(self, idx, obj):
curObj=obj
nextObj=None
pos=(self.startPos+idx)%self.size
while idx <= self.count:
pos=(pos+1)%self.size
nextObj=self.array[pos]
self.arry[pos]=curObj
curObj = nextObj
idx+=1
def popFirst(self):
if self.count == 0:
return None
retObj = self.array[self.startPos]
self.startPos = (self.startPos+1) % self.size
self.count -= 1
return retObj
def pop(self):
if self.count == 0:
return None
pos = (self.startPos+self.count) % self.size
retObj = self.array[pos]
self.count-=1
return retObj
def size(self):
return self.size
def toList(self):
retList = []
for obj in self.generator():
retList.append(obj)
return retList
|
def solve(arr, duration):
if len(arr) == 0:
return 0
result = 0
start = arr[0]
for i in range(1, len(arr)):
if arr[i] - arr[i - 1] > duration:
result += arr[i - 1] + duration - start
start = arr[i]
result += arr[-1] + duration - start
return result
A = [1, 2, 3, 4, 5, 6, 7, 8, 9]
B = 5
print(solve(A, B))
|
class Solution:
def setZeroes(self, matrix):
rows, cols = set(), set()
for i, r in enumerate(matrix):
for j, c in enumerate(r):
if c == 0:
rows.add(i)
cols.add(j)
l = len(matrix[0])
for r in rows:
matrix[r] = [0] * l
for c in cols:
for r in matrix:
r[c] = 0
|
""" Base Controller for interacting with the Scene """
class BaseController:
def __init__(self):
super(BaseController, self).__init__()
def start(self):
raise NotImplementedError()
def reset(self, scene_name=None):
raise NotImplementedError()
def step(self, action, raise_for_failure=False):
raise NotImplementedError()
|
#DESAFIO 13: REAJUSTE SALARIAL
#Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento.
salário = float(input('Qual é o salário do funcionário? R$'))
novo = salário + (salário * 15 / 100)
print('Um funcionário que ganhava R${:.2f}, com 15% de aumento, passa a receber R${:.2f}'.format(salário, novo))
|
counter = 0
b = 106700
c = 123700
step = 17
for target in range(b, c + step, step):
flag = False
d = 2
while d != target:
e = target // d
if e < d:
break
if target % d == 0:
flag = True
#print("d: {0:d} e: {1:d} b: {2:d}".format(d, e, target))
break
d += 1
if flag:
counter += 1
else:
print("Prime: {0:d}".format(target))
print("{0:d}".format(counter))
#905 is correct
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def sayHello(self):
print("Hello my name is {} and I am {} years old".format(self.name, self.age))
worker = Person("Alina", 21)
print(worker.age)
print(worker.name)
worker.sayHello()
|
def partition(a,l,r):
#assert: Previous proof but partitions between l and r
# It considers the first element as a pivot and moves all smaller element to left of it and greater elements to right
x=a[l]
n=len(a)
i=l
j=r
while(i<j):
if a[i]>=x and a[j]<=x:
a[i],a[j]=a[j],a[i]
i+=1
j-=1
elif a[i]<x:
i+=1
else:
j-=1
return(a,i)
def kth(a,l,r,k):
if (k>0 and k<= r-l+1):
# Partition the array around last element and get position of the pivot element in partioned array
(array,pos_i)=partition(a,l,r)
# if position is same as k
if (pos_i-l==k-1):
return a[pos_i]
# If position is more then k, apply recursion for left sub array
if (pos_i-l>k-1):
return kth(a,l,pos_i-1,k)
else: #apply recursion for the right sub array
return kth(a,pos_i+1,r,k-pos_i+l-1)
else:
return ": Seriously? Imagine asking for 7th biggest slice of pizza with 6 pieces"
arr = [12, 3, 5, 7, 4, 19, 26]
n = len(arr)
k = 2;
print(k,"th smallest element is",kth(arr, 0, n - 1, k))
#Time Complexity:
#The time comlpexity depends upon the pivot chosen
#If the pivot decreases size of array by 1 element (Worst case) the time complexity is O(n^2)
#If the pivot decreases size of array by some fraction (Maybe n/2) (Best case) the time complexity is O(n) (=n/2+n/4+n/8+.... < n)
|
user_createaccount = []# Empty user_create account
class User:
def __init__(self,username,password,email):
"""
created insatances of the user class
"""
self.username = username
self.email = email
self.password = password
User.user = {"username":self.username, "email":self.email, "password":self.password}
def save_account(self):
User.user_createaccount.append(self)
def generate_password():
pass
@classmethod
def return_user(cls):
return cls.user
|
'''
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
Runtime: 20 ms, faster than 99.90% of Python3 online submissions for Partition List.
Memory Usage: 14.1 MB, less than 100.00% of Python3 online submissions for Partition List.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def swap_node(x, y):
tmp = x.next
tmp1 = y.next.next
x.next = y.next
x = x.next
x.next = tmp
y.next = tmp1
return x, y
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
if head is None or head.next is None:
return head
first = ListNode(-1)
first.next = head
p = first
while (p.next):
if p.next.val >= x:
in_pos = p
break
p = p.next
if p.next is None:
return first.next
while (p and p.next):
if p.next.val < x:
in_pos, p = swap_node(in_pos, p)
continue
if p.next is None:
return first.next
# elif p.next.next is None:
# prev = p
p = p.next
if p.val < x:
tmp = in_pos.next
in_pos.next = p
in_pos = in_pos.next
in_pos.next = tmp
prev.next = None
return first.next
|
# coding=utf-8
# See main file for licence
# pylint: disable=W0401,W0403
#
# by Mazoea s.r.o.
#
"""
Tesseract constants.
"""
size_of_int32 = 4
NUM_CP_BUCKETS = 24
CLASSES_PER_CP = 32
NUM_BITS_PER_CLASS = 2
BITS_PER_WERD = (8 * size_of_int32)
BITS_PER_CP_VECTOR = (CLASSES_PER_CP * NUM_BITS_PER_CLASS)
WERDS_PER_CP_VECTOR = (BITS_PER_CP_VECTOR / BITS_PER_WERD)
CLASS_PRUNER_STRUCT_SIZE = NUM_CP_BUCKETS * \
NUM_CP_BUCKETS * NUM_CP_BUCKETS * WERDS_PER_CP_VECTOR
PROTOS_PER_PROTO_SET = 64
NUM_PP_PARAMS = 3
WERDS_PER_PP_VECTOR = (
(PROTOS_PER_PROTO_SET + BITS_PER_WERD - 1) / BITS_PER_WERD)
MAX_NUM_CONFIGS = 64
WERDS_PER_CONFIG_VEC = ((MAX_NUM_CONFIGS + BITS_PER_WERD - 1) / BITS_PER_WERD)
NUM_PP_BUCKETS = 64
PROTO_PRUNER_SIZE = NUM_PP_PARAMS * NUM_PP_BUCKETS * WERDS_PER_PP_VECTOR
# dawg
FORWARD_EDGE = 0
BACKWARD_EDGE = 1
MARKER_FLAG = 1
DIRECTION_FLAG = 2
WERD_END_FLAG = 4
LETTER_START_BIT = 0
NUM_FLAG_BITS = 3
#
PICO_FEATURE_LENGTH = 0.05
PROTO_PRUNER_SCALE = 4.0
INT_CHAR_NORM_RANGE = 256
PROTOS_PER_PP_WERD = BITS_PER_WERD
PRUNER_X = 0
PRUNER_Y = 1
|
# Copyright 2020 Rubrik, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
"""
Collection of methods for live mount of a virtual machine.
"""
ERROR_MESSAGES = {
'INVALID_FIELD_TYPE': "'{}' is an invalid value for '{}'. Value must be in {}.",
'REQUIRED_ARGUMENT': '{} field is required.',
'REQUIRED_KEYS_IN_CONFIG': "Config field should contain datastoreId, hostId or clusterId and snapshotId.",
'INVALID_CONFIG': "'{}' is an invalid value for field config."
}
def create_vm_livemount(self, snapshot_fid: str, host_id: str = None, vm_name: str = None, disable_network: bool = None,
remove_network_devices: bool = None, power_on: bool = None, keep_mac_addresses: bool = None,
data_store_name: str = None, create_data_store_only: bool = None, vlan: int = None,
should_recover_tags: bool = None):
"""
Perform a live mount of a virtual machine snapshot.
Args:
snapshot_fid: The Snapshot FID of the snapshot.
host_id: The Host ID.
vm_name: The VM Name.
disable_network: Whether to disable network.
remove_network_devices: Whether to remove network devices.
power_on: Whether to power on.
keep_mac_addresses: Whether to keep MAC address.
data_store_name: Name of the data store.
create_data_store_only: Whether to create data store.
vlan: VLAN ID.
should_recover_tags: Whether to recover tags.
Returns:
dict: Dictionary containing live mount information
Raises:
RequestException: If the query to Polaris returned an error
"""
try:
snapshot_fid = self.validate_id(snapshot_fid, "snapshot_fid")
query_name = "gps_vm_livemount"
variables = {
"snapshotFid": snapshot_fid,
"hostID": host_id,
"vmName": vm_name,
"datastoreName": data_store_name
}
if disable_network:
variables['disableNetwork'] = self.to_boolean(disable_network)
if remove_network_devices:
variables['removeNetworkDevices'] = self.to_boolean(remove_network_devices)
if power_on:
variables['powerOn'] = self.to_boolean(power_on)
if keep_mac_addresses:
variables['keepMacAddresses'] = self.to_boolean(keep_mac_addresses)
if create_data_store_only:
variables['createDatastoreOnly'] = self.to_boolean(create_data_store_only)
if should_recover_tags:
variables['shouldRecoverTags'] = self.to_boolean(should_recover_tags)
if vlan:
variables['vlan'] = int(vlan)
response = self._query_raw(query_name=query_name, variables=variables)
return response
except Exception:
raise
def create_vm_snapshot(self, snapshot_id: str, sla_id: str = None):
"""
Create snapshot of a system.
Args:
snapshot_id: The Snapshot ID of the snapshot that needs to be created.
sla_id: The SLA ID of the snapshot that needs to be created.
Returns:
dict: Dictionary containing snapshot information.
Raises:
RequestException: If the query to Polaris returned an error
"""
try:
variables = {}
snapshot_id = self.validate_id(snapshot_id, "snapshot_id")
variables['snappableId'] = snapshot_id
if sla_id:
variables['slaID'] = sla_id.strip()
return self._query_raw(query_name="gps_vm_snapshot_create", variables=variables)
except Exception:
raise
def list_vsphere_hosts(self, first: int, after: str = None, filters: list = None, sort_by: enumerate = None,
sort_order: enumerate = None):
"""
Retrieves a list of available Vsphere hosts.
Args:
after: The next page cursor to retrieve the next set of results.
first : Number of results to retrieve in the response.
filters: Filters the SLA result. Supported fields of class GlobalSlaQueryFilterInputField.
sort_by: Sorts the result using HierarchySortByField.
sort_order: Sorting orders ASC or DESC.
Returns:
dict: Dictionary containing list of Vsphere hosts.
Raises:
ValueError: If input is invalid
RequestException: If the query to Polaris returned an error.
"""
try:
variables = {}
if not first:
raise ValueError(ERROR_MESSAGES['REQUIRED_ARGUMENT'].format("first"))
first = self.check_first_arg(first)
variables['first'] = first
if isinstance(filters, str):
filters = [filters]
if filters:
variables['filter'] = filters
if after:
variables['after'] = after.strip()
if sort_by:
supported_sla_sort_by = self.get_enum_values(name="HierarchySortByField")
if sort_by not in supported_sla_sort_by:
raise ValueError(ERROR_MESSAGES['INVALID_FIELD_TYPE'].format(sort_by, 'sort_by', supported_sla_sort_by))
variables['sortBy'] = sort_by
if sort_order:
supported_sla_sort_order = self.get_enum_values(name="HierarchySortOrder")
if sort_order not in supported_sla_sort_order:
raise ValueError(
ERROR_MESSAGES['INVALID_FIELD_TYPE'].format(sort_order, 'sort_order', supported_sla_sort_order))
variables['sortOrder'] = sort_order
return self._query_raw(query_name="gps_vm_hosts", variables=variables)
except Exception:
raise
def export_vm_snapshot(self, config: dict, id_: str):
"""
Export a snapshot of a virtual machine.
Args:
id_: The object ID.
config: Configuration parameters for exporting snapshot.
Returns:
dict: Dictionary containing snapshot information.
Raises:
ValueError: If input is invalid
RequestException: If the query to Polaris returned an error
"""
try:
variables = {}
id_ = self.validate_id(id_, "id_")
variables['id'] = id_
if not config:
raise ValueError(ERROR_MESSAGES['REQUIRED_ARGUMENT'].format("config"))
if not isinstance(config, dict):
raise ValueError(ERROR_MESSAGES['INVALID_CONFIG'].format(config))
data_store_id = config.get('datastoreId', '')
host_id = config.get('hostId', '')
cluster_id = config.get('clusterId', '')
snapshot_id = config.get("requiredRecoveryParameters", {}).get("snapshotId", '')
if not data_store_id or (not host_id and not cluster_id) or not snapshot_id:
raise ValueError(ERROR_MESSAGES['REQUIRED_KEYS_IN_CONFIG'])
variables['config'] = config
return self._query_raw(query_name="gps_vm_export", variables=variables)
except Exception:
raise
def list_vsphere_datastores(self, host_id: str, first: int = None, after: str = None, filters: list = None,
sort_by: enumerate = None, sort_order: enumerate = None):
"""
Retrieves a list of datastores on a Vsphere host.
Args:
host_id: The Host ID.
after: The next page cursor to retrieve the next set of results.
first : Number of results to retrieve in the response.
filters: Filters the SLA result. Supported fields of class GlobalSlaQueryFilterInputField.
sort_by: Sorts the result using HierarchySortByField.
sort_order: Sorting orders ASC or DESC.
Returns:
dict: Dictionary containing list of Vsphere datastores.
Raises:
ValueError: If input is invalid
RequestException: If the query to Polaris returned an error.
"""
try:
variables = {}
host_id = self.validate_id(host_id, "host_id")
variables['hostId'] = host_id
first = self.check_first_arg(first)
if first:
variables['first'] = first
if isinstance(filters, str):
filters = [filters]
if filters:
variables['filter'] = filters
if after:
variables['after'] = after.strip()
if sort_by:
supported_sla_sort_by = self.get_enum_values(name="HierarchySortByField")
if sort_by not in supported_sla_sort_by:
raise ValueError(ERROR_MESSAGES['INVALID_FIELD_TYPE'].format(sort_by, 'sort_by', supported_sla_sort_by))
variables['sortBy'] = sort_by
if sort_order:
supported_sla_sort_order = self.get_enum_values(name="HierarchySortOrder")
if sort_order not in supported_sla_sort_order:
raise ValueError(
ERROR_MESSAGES['INVALID_FIELD_TYPE'].format(sort_order, 'sort_order', supported_sla_sort_order))
variables['sortOrder'] = sort_order
return self._query_raw(query_name="gps_vm_datastores", variables=variables)
except Exception:
raise
def get_async_request_result(self, request_id: str, cluster_id: str):
"""
Retrieves the result of an asynchronous request. These requests can be triggered by calling functions such as
export_vm_snapshot, create_vm_livemount, request_download_snapshot_files or create_vm_snapshot.
Args:
request_id: The ID of the asynchronous request.
cluster_id: The ID of the cluster where the request was made.
Returns:
dict: Dictionary containing the result of the request.
Raises:
ValueError: If input is invalid
RequestException: If the query to Polaris returned an error.
"""
try:
query_name = "gps_async_request_result"
variables = {}
if not request_id:
raise ValueError(ERROR_MESSAGES['REQUIRED_ARGUMENT'].format("request_id"))
variables['id'] = request_id
if not cluster_id:
raise ValueError(ERROR_MESSAGES['REQUIRED_ARGUMENT'].format("cluster_id"))
variables['clusterUuid'] = cluster_id
return self._query_raw(query_name=query_name, variables=variables)
except Exception:
raise
|
def factorial(n):
fact=1
for i in range(1,n+1):
fact*=i
print(fact)
factorial(5)
|
print('''@#############################################################MMMMMMMMMMMMMMMMMMBBBBMMMMBB&AMBAHM###MMMMMMM#
@hG&&AA&&A&G&&&&GG&AA&&&&&AAAAAA&&&G&&&GGhh&AAAG93XX39h93X225iiiS5SSSSSSSiSiSSisssssiisssi:.;s;iXX25Sii25SSA
@hAAHAAHAHAAAAAAAAAAAAAAAAAAAAAAAHHHAAAG&&3Ssi5G&GG&&GG9333X2552222222255525rrSSS55SSSiSS5X;:Xri2SX252r ;A9A
@GAHHHHHHAAAAAAAAA&AAAAAAAAAHHHAh25iiS29B@Hr sAX9GAAGh3333XX22222XXX5iS55Sii552225SS2X2iih&A: ,;X22r:;:ihA
@GAAHHHHAAAAAGG&&&G&&&AA&AA&XSsii55Sirrrs&@#r s::::r53h9XX3X252252XX2SiiiiS55525SS5irr239GGAHX39222XA3,:hA
@3GAAAAA&AAAA&GGGGhhhGGGGG2i2hAAhir;:. G@9 .;....:;rr53X25SS5552225rrisiSSiiiiiiir:Shh9999;iX223G&hAA9&
@29&G933GAAAAA&Gh933393&MMM#@HXs:,:,, ,@@, r, ,;;;r52SiiSiiiiisrsiissssrsssSXh399X2222222X99hGAHh&
#5XX2X999hhGGGGGh33XXX2B#AH#MGir:::,,. r@A ,r ::,:iSisssrrsssssssrrrssss5X3XX2222riX2X3333G5.;&
#iS52XX222222X99993XX2X##323HMB9Sr;;;, &@; s, ;;.:srsssrrrrrrr;r;rrsiSS5522252222X3333X3h2:rG
#iS22255225222XXXXXXX5G@#X3#AGAB#A2rrr;, ,@A. ;s, .AS ssrssrrrrrrr;rrrssiiSSiS555222sr9XXX339GA3G
#s52222222552XXXX22225M@Ai####H3X3hAAG2i;, ,#@r. :Sr. ,;; ,srrr;rr::;;;rrrrssiiiiSS55222XSs22S2399332h
#s522222255SSSS22252SX@@2;MAX29H#B&XS2HA&32ssA@X;:;Xs;::;sirr::r5rrrr;;;:::;;rrrrrsssssiSSSri3X95S3X33XXXX59
#s5X22222255SiiiSSSSiA@@;5#Xr;;;r5&MMH@#3S5H&B@@2:,SMhSSi:i2ss;.rsrr;;;;;;;;rrrrrrsssii5252rsXXis933X22XX2i3
#i52222222225SSiiiiis#@B:HMXs:,,,...:r2B@@##AA@A;.. @@A2Sr;, .ssr;;;;;;;rrrrr;,,rsiSSi:rX3X23i;XX255225SsX
#i52222222225SSiiisr5@@&r#HXr;:: .;h@@@@G: #A:, rSr;;;;;;rr;rrrr;..riSi,;;;2X22X9hXX2555Siir2
#i5XXXX2222555Siiis;A@@9i#G2ir;;,. :A#@A. A; .ir;;;;;;rs;:rrrrr::sSiS;;93X2X922X2225SSiiir2
#i2XXXXXXX2255SSiirr##@3XB35Siii;:,.. h#@h;. ,B, :r;;;;;;rrrrrrrrsi;r5iS232Sr.i2r;;25,:2, s5is2
#SX9X33XXXXX255SisiB@##&&AX2SiiSi;;:. ,A#@X; ;A. ..;r;;;;rrrrrrrrrsr;ri22222Si::X5,r5Ss:rSr;sr X
@23h333333XX225SirB@###AH&X2ssrrs;;:...,. rA#@5;, X9, . rr;:;rrrrrrrrrsisrSrr55522X5iiX32SSss5ir2srrrX
@39hhhh9333XX25isr#@MGB#M&2irr;;;::;,,,,:,,iH@#i:, A2:,,. .rrr;;rrrrrrrrrsriS5s;5SS5irX2525iiS5SSSSSS5X23
@X9GGGG993XXX2Siri@##s:A@#G5sr;:,::::;:,. .5#@Mr:,,BS;;:, .,;rrrr;;;;rrr;rssrsiS5iriSSSS55SiiiSiiiSSiiS22SX
@XhG&&GGh93X25Sir9@#B9XAH&#@HXi;:,,,,,,,,,;G##A;:,iMrrr;:..:rirr;;;;,;rr;,r;;siiiir;iiiiiiiiiSSiiiSSSiS2XXiX
@3h&&&GGh93X25Sir3@#HhA@M2:;B@@#AXr,.,,,, :A##3;;;AHsr;:;rr3X:r;;;;;;rr;:rrrrsrssssiiisssssiiiiiiSSSS22XX2iX
@3h&AGhh9XXX25Sir3@##&B#AGhsi2A#@@@#Ah9&hi2##M3r;r#Mh95i9A&2 ,;;;;;;;;;;;;rsisrrrrsssrsssssissssiiSS52XX25s2
@3GA&Gh933X225Si;&@#AAM##Gi;..,:;;rS3GH#@@@@##@MB#@MAHBH&S: :r;;;;;;:,:r;;;,..rrrrrrrrrr,;ssrrsssii552225Sr5
@3GGGGh993X22SSi;X@MGAAXG#BS:. :9M2:,,2@r.;;, ;;;::::;,:;;;;: ,:;;;;;;r;;rr;rrrsiiiS55SSSirS
@3hhhhh93XX25Sis;&@MBBAr.rH@#hr, i@#X, :Mr. :;:,:::::,:;;;;;;rr:,:,;;;;;;r;;,;rrrsssiiiiiis;S
@X39h9933X22SSisrM@MAH#M9iX@@@@B5r:, .i@Hr: rs .;: ;;s222srrr:,,,::::;:,:::,;. :;;;;;;;;rrrsrrrsrr;i
@X99993XX225SSiri@#AXAMM#BXh@@@@@@@@#BGX2SAM#&;rXG;:SB@@@sr2M@@#2:sXAHhi;;;;r. ;;::,,,,::,,:;iS23h22s;rr;;:s
@X993XXX225SSisr3@#BAHBXSX2;;h##@@@@@@@@@@#M@#X&@@@@@@@H. ;G@MB&;;2isS9HMHA3i:;XHMXis,,:,;S&&3##H2;:,:::,::s
@X393X2225Sii35s&###BMM3sr;r5H#&ii5GMBAM@@@#@@H@@@Hr. ;i r##GGr ;srr;;,, :. :rsXM92@HGA#@@2 .hH&G&hX5i593SS
@2X3XX225Sii2#@@#HH###Mh2i;,;HAs:. ,,,:5ABX;,.Xi 2 2@A&G3Srrrr:::,,:::,,;iAAM@@@@@#HH3iGG99h&H##AX;, r
@2XXX22SS2A#@@@@##M###M&hhiri#&:., :A@Bi: ;r i:5@B3sX25ir;;:,,,,,,,:.:sS&h#@@#MHA&AHGXXX3hhG&3srr;s
@2XX255XhM@@@@#######@@#HAhX&@Hr:;: .H@X:is;r:. :S5@MGr.:;;:,:r;;r;,. .:. s2H@#@@MA&G&&Ss33333h99G&GH#A
@2Xh93MBA@@@#######BB#@@@BAAM#AXi;rr. .A@9:,::r:. S3#AX;,.. .,,.:s;,:,, .rs:2A@@Mr;GAGh9h;:3XXi.S33GAA&3&
@X2Si29A@@########B95XB@@@BBB#B&&Srs; .S#@MA2;rr. :MAGs:,.,,,,::, ,:.:r5r;9A2XM@#&..&BAGG&A&933X2X3X9hAHHH
#3h2SisSB#BBM##M###A52M#M@##MH&3Xir;:,,;X@#i;;:S; .HH5i, .,:,::,;, .;;s2939#H9A@@#@@@BG9X999333339X222X9hGH
#2M###A9XBMM#BHBMMMAA##AXG@###ASr;;;:,:;3#3;:,;G;,:AArrr..::;,;:.:;,rh5s9AAM#A&##HHHHAh3XXX3GG3393X2X3X2252A
#sA#M#@#AA#@#&AHAHHH##HA5.:M#3A@hr;;::,:9MAi5,S2:;Ghr;s;,:;:;:;;;;rr3hiiAHAAAXA#MBHAAh9hhGGs :XG9339Gh3XX99A
#iGA2hHMBHHAGGAAGGH#@BAB3 i@@r:M@9r::,:9#B:,:&r;A2s;rssr;;;::srrss5hXiXABBBHB@MHA&AA&&&&&&i iAhGAAG3XXX39A
@2AHir59MB5rsXAMBAM#AGGAX:;Ar.s, rGM9r:sX#G;.2@BGX;r,;i32iir;r5r5X2AAS2#@@####MMBAGGGX23X9&AMHA&&GhhX22XGAAB
@GHAirShHASi2&&AAAAA99hXsiMG .9#G&@@@#@##B2r@#Ss;;: ,iXXXh2rhh2&GAH2SM@@###MHAAAAhh99h&HiiBHHA&Ghhh9GAAHAAB
@AAA9GHAHMHBBAhGA&H@BGHHA@@5SB@@@##MBMMBHAB&Xr,,,,;,.rXrShh5S9SX3G&s5@@@#MBHHHAA&GAAAAHAA99BAA&&GGGh3hGAAAAH
@9&HMBBAMBMBAhAA93&BHGGhAB#M@@M35sr;;:;rSXX;. ,.,;:;X&S9XsrsriA@A;s@@#MMMBHHHHBh;X&&&AX;iHG&&&GhhGGAAAAAHHM
@9AMMMBAhX523&AXS2hhXXhhXX9GGh5srr;;::;i93r:.:2SrS35iA&GAi;r5SH#5:i@@#MBBB#MBHBBM9BBA22BMBAGG&AAHMBAAG9hh&AB
@GGAA32sr;;sSii2XG9irS5522X3XX99hGA&&9hAhS;:;X9siA&52A222Si3AA2;i33@#ABMBH&GHHX3BHM##MX9&AHBHHB#@G3HH&G93X2A
@#H&h333335iiiXX3S;;ihSsi5X9hhh&A&G9GGh2sr;rAA22h5:;3HA3i3MBAX9@@@##BBM2hMS9HHSriAsGBM#BAGAHMM#2 .GAHAAGXA
@BMMM#MAAA9Xh&3h2si5XG5sr;;rsiisssiSirrrsrXBA9GA5::2H9&A2SXG#@@@@@##MBM55MHM##@@#@#G&AHHAAAAB@s G#AHAHBB
@&ABB#####HH&X399G3X22iS5Sr:;;::sSSs;ri52GH&h3X2SXG95r:,sA..:s9A#@@#@MM@@M###@H. 2@MAAHHHB## :;sA@@#BHA&B
@&A&AHBM#@@@@MHAGGh3222239X25ShMX552hHHB#@#&GAHMBG5r:,s#@X.:;;;2@@BB##@####MM@ S@@#####@B ,X@@##MMBAB
@A&HBHMMBH##@@#MMM##@@@A9A#HG@@@@GAHH#@#&X5SsiXS;, :B@@r .... r@G;H@####BMB#@: ,rr;2@@@@@@@@2;sH@#@@MMMBBAB
@AB#HAHBBH2G2S5X3933hAMMAGX5s#@@@s;rr;::... .9@@X S#@#####M#@@ ,rs.r@@@@#2s:rG@@#@##HBBBAB
@HMM359GAirs;;rr;;;;:::::,,, G@@@: ,2H@@M. :, ;H@@#####@@@ ;Si;X; s. i@#&B@MHHHAM
@ABX2@&s;:;;rr;::,,. #BA#, 2@@@BBB . :rrSir;:9@@#####@@@..;;2r i ;2M@#H#MHHHHAB
@&Xrr9@@B2r;,.,... r@93M; ;#@#BBXr ....:H#5M###@@2.;;.;r. S#AGH@@MHHM@#BAHAB
@r;sirS@@@@@&: ... ..... ,@AA#H h@@BA#s .,, ;Hi#@@@3 r92:GG@@@@@@#&M#HBMMA&B
#r532i;:A@@@@@5 .,:::;;:,.. 5@HH#@, ,HB&AA#2 ..,r. 2@. . ;A#HB@@@@@@@M@B##MAGHBB
#S22i;;,.:i@@@@@r, ,@#M#@@ 5@@AhAA: ... Xr :, 3M3s@@@@#M@#@BH#HH#MhH
#iiirrr;:. 2@@@@@&s: .. B@#@@@; .B@Bh9A9 ,,r..r. ,A; .r. ,2AAM@@@@@@M@AA99MAMHM
#sssssrr;:,. 3@@@@@@@; 5@3rrsX#@@@A3r2& ., ...,r:rh, XA;:,. r&MM@@#@@H#A&H929G#AB
@iSisrrr;;;,. r@@@@@@@@&Sh@B, ..:s&#B&M s&; .:r;2, i2rsX; ,5;2hs;XGH#@@@@MM#BB#9hhX&5A
#iSisrrrr;;::, ,r9@@@@@@@2.,;;;;rr:..i#@5 . .. :XBX; :;. ;Air;,s:,H@@@M#h 2@@@@@#A@B&3SA
#iiirrr;;r;;:, ,A@@@M;5X222H@B3ir:3@#2AHHAA&GG9#r . .9hA@@#9s ;r. .2,r@@A5X3@@#@#. 5@@@@@@@@@#HAXA
@SSiisisr;;:,.. :#@#H@@BHHA@@@@@, M@@@@@@@@@@@@#&i :;2@@#B@#X; , ,sH#A#@#XG##AB@X .;Sh&@@@@B&A
@XXXXXSr;:::,,:::::,,:;rH@M@@@#35A&s29i,,@@#AM@@@@@@@@@@@@@5 . .#@@s , ,. .H@@HhX3HMH3S5#@B; s@@#H
@&&h2s;;;;;;;;r;;r2H@@@@@@XhHMhGA@2;59GA9@@@MGSr;:,,,,,,r#@@#s: , r@@#@53:s,A@@@#AAHHhXi:,s@@#r 2@#
@XXSrr;;;rrsrrS&@@@@@@@@@@M&AHB#@#&hGG92r2@s 9@@@Ar . .A@@@@#@###M###MBAh99i;.,5@@X:, :. :@
@iissiissiS3M@@@@@@@@@@@#@@G&hG#MMHA2r;:,h#B5 S@@@#&:rAB@@@@@@@##A&&ABMHh3GGS;. .3@B;:;, sA,X
@issS252&#@@@@@@@@#H3Sr.,#@2isssi2;::,.:h#AH@@i ,9@@@@@@@@@@@@@#A3X3&H#MHAGh2s;. ,9#5,;;.;AG
#rs552B@@@@@@B9Sr;:.. ;@@@#Srr;:,,,.,&HBA59H#@B. .2BX, ,2AB##&iiX39HMHHh32r:. .9#r.,:5h
#59A@@@@@B3ir;:::,:::,i@@@@@@@GSsrrs3@9 . 5#MM@@i .iH@AsrssSAHA#A&2;, ,AG;2;r
@h#@@#&2isrr;;;:;;;r;r@@@@@@XA@@@@@@@, .i@@#@@#: ..,.,::..rh@#XsrrSAAG@BAs:, r@@ :
@AMHhX2Ssrrrrrrssiii9@@@@@@r :@@@@@A .. .M@@@@@&; .,,;;rrr;S5##S;;riA3X@#As:, :@2 .
@AA&32irrrrsi5222iS#@@@@@@r ,..@@@#@A ... ;hM@@@@@X :r25is;##, :;sBS2@#ASr:::,:h& :
@GG32Siiii52X22i;2@@@@@@9. .. ##AA#5 r@@@@@; ... .... ,;s5X:;;#A .;s#i5#HG2iss2M&. :
@9hh3XX39h925Ss;A@@@@@X. .. S@BH#2 A@#@@h ...... ..:;rrsX: r:#A ,;#r2#AAAM@@2: . i
@&HBHHHAGXSsssr#@@@@h, ,:::;:..@@@@@ .,,,,..... ;h@@@@, .:::....;siri, ;,#H, :M;A#B#@3;;:r,;@
@A##BHAGX55SSr2@@@A;,:riiSiiisr,r@@@@i,;;;;:;;,,:;::, .s#@@A .:;rr:,:;;i@,ii,MHr,:rB#i#@9r:,.r,;@@
@A##BA&9X2225rB@@G:ri522222255ir:@@@@3;s;ssrr;,.,,,. i@@2,... .,;iSi;:r@@@@S,&h&@@#@##M2i ,:X@@#
@&HMHG3Xisiir#@&s:;rssrrr;::;r;;,&@@@G.:,,.. S;.,,:,,. ,r3&3rB@#5@h;rs9@#&32A#HSsG@@@XH
@&AB&3X2Sssri@s .,:::::::, ,,,. 5@MG. .,,::,:::::,.. .,,::::::;i2X@@#;s@#XS::53XS2M@@@@@MMAA
@AHA&G325Sisir,:::,,,,,.. @@9 ,;;;rsis;rr;;::,........... .:rirr;rr;9@@@H#@@@MAM@@@@@@@@@@@MB#
@h3XXX333X2ir;;;;;;;;;:,,,,,,... A@@,;rsiiSSiiiir..:,.. ..,:;;;;rsiri&###@#@@@@@@@@@@@@@2r293iH
#255issiiSSSiisr;;;;::;,:;;;;rrrrriBHsssi;,;rrrr;;;:::,,,.. .,::;;rrrs2BMBMMMMBMM#@@@@@@@#9XS292A''')
print('''The way I see it, our fates appear to be intertwined.
In a land brimming with Hollows, could that really be mere chance?
So, what do you say? Why not help one another on this lonely journey?''')
choice = input('Choose fellow warrior.\nYes or No?\n').lower()
if choice == 'yes':
print('Lets get going then.')
print('I am bored now, so bye lul.')
else:
print('Ahh warrior, so you decided to continue your own adventure. \
Then I shall not bother you for I too have to seek my own sun')
|
class InvalidTraceHeader(Exception):
"""Thrown if a bad trace header was passed in."""
class InvalidMessageID(Exception):
"""Thrown if a bad message id was passed in."""
|
# SETTINGS FILE
# TOKEN - discord app token
# BOT PREFIX - no explanation needed (uhh I think)
# API_AUTH - hypixel api auth
# DB_CLIENT - your DB URI
# DB_NAME - no explanation needed
# APPLICATION_ID - discord app id
TOKEN=''
BOT_PREFIX='$'
API_AUTH=''
DB_CLIENT = ''
DB_NAME = ''
APPLICATION_ID=''
|
# -*- coding: utf-8 -*-
class Symbol(object):
def __init__(self, symbol):
self.number = int(symbol['number'])
self.numberEx = int(symbol['numberEx'])
self.name = symbol['name']
self.var = symbol['var']
def __str__(self):
return '\t\t\t\tNumber: {0} \n\t\t\t\tNumberEx: {1} \n\t\t\t\tName: {2} \n\t\t\t\tVar: {3}'.format(self.number, self.numberEx, self.name, self.var)
|
def mutate(soup):
paragraphs = get_max_paragraph_set(soup)
headline = soup.find('h1')
html = str(headline) + '\n'
for paragraph in paragraphs:
html += str(paragraph) + '\n'
return html
def get_max_paragraph_set(soup):
paragraph_map = build_paragraph_map(soup)
key = get_max_key(paragraph_map)
if key is None:
raise NoParagraphsError()
return paragraph_map[key]
def get_max_key(paragraph_map):
max_count = 0
max_key = None
for key, paragraphs in paragraph_map.items():
count = len(paragraphs)
if count > max_count:
max_count = count
max_key = key
return max_key
def build_paragraph_map(soup):
paragraph_map = {}
for paragraph in soup.find_all('p'):
key = id(paragraph.parent)
if key not in paragraph_map:
paragraph_map[key] = []
paragraph_map[key].append(paragraph)
return paragraph_map
class NoParagraphsError(RuntimeError):pass
|
a = 3
while a >= 3:
print("CSK Wins")
break
user_input = input('Enter City')
while user_input == 'Chennai':
print('Chennai pasanga da')
break
user_in = input('Enter Country')
while type(user_in) == str:
if user_in == 'India':
print('India is the best')
break
else:
print('Other country is the best')
break
genre = input('Enter your Genre ')
movie = input('Enter the movie ')
if genre == 'Horror':
print(movie,'is the best horror movie')
else:
print(movie, 'is different genre')
|
letters = 'aeiou'
txt = input("Podaj tekst: ")
txt = txt.casefold()
count = {}.fromkeys(letters,0)
for ch in txt:
if ch in count:
count[ch] +=1
print(count)
|
"""
Theory
> Instance vs Class
> Attributes, methods, inheritance, polymorphism
"""
class Scout():
pass
ratarca = Scout()
|
#!/usr/bin/python3
class Line:
def __init__(self, x1, y1, x2, y2):
self.x1 = int(x1)
self.y1 = int(y1)
self.x2 = int(x2)
self.y2 = int(y2)
self.rangex = abs(self.x2 - self.x1)
self.rangey = abs(self.y2 - self.y1)
def print(self):
print(str(self.x1) + "," + str(self.y1) + " -> " + str(self.x2) + "," + str(self.y2))
def check_for_touch(self, line):
touches = 0
for y in range(self.rangey):
for x in range(self.rangex):
print(x,y)
# for y in rangeY:
# print(y)
# for x in rangeX:
# print("this: " + x,y)
# if line.is_on(x, y):
# touches += 1
return touches
def is_on(self, ax, ay):
for y in range(abs(self.y2 - self.y1)):
for x in range(abs(self.x2 - self.x1)):
startx = self.x1
starty = self.y1
print("is_on")
if self.y1 > self.y2:
starty = self.y2
if self.x1 > self.x2:
startx = self.x2
if startx + x == ax and starty + y == ay:
return True
return False
def show_result():
counter = 0
while(len(lines) > 1):
line = lines[0]
lines.pop(0);
for l in lines:
counter = counter + line.check_for_touch(l)
return counter
input_file = open("sample.txt")
input_text = input_file.read().split("\n")
coords = []
for coords_raw in input_text:
coord_raw = coords_raw.split(" -> ")
coord = []
for c in coord_raw:
new_coord = c.split(",")
coord.append(new_coord)
coords.append(coord)
lines = []
for c in coords:
start_coord = c[0]
end_coord = c[1]
if start_coord[0] == end_coord[0] or start_coord[1] == end_coord[1]:
lines.append(Line(start_coord[0], start_coord[1], end_coord[0], end_coord[1]))
# print(len(lines))
print(show_result())
# for l in lines:
# print(l.print())
|
# -*- coding: utf-8 -*-
"""
@time: 2020/3/19 10:31 上午
@desc:
"""
class SQLFormatError(Exception):
pass
class ParameterError(Exception):
pass
class ConnectError(Exception):
pass
class ExecuteError(Exception):
pass
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
# handle exceptions
if head==None or head.next==None:
return head
prehead = ListNode(val=-1000, next=head)
pre = prehead
curr = head
post = head.next
counter = 1
while post:
# traverse continuous duplicates
while post.val==curr.val:
post = post.next
counter += 1
if post==None:
break
if post:
if counter==1: # if no continuous duplicates exist
pre = curr
curr = post
else:
curr = post # if continuous duplicates exist
pre.next = curr
counter = 1
post = post.next
else:
if counter==1:
curr.next = None
else:
pre.next = None
break
return prehead.next
|
# -*- coding: utf-8 -*-
# Author: Daniel Yang <daniel.yj.yang@gmail.com>
#
# License: BSD 3 clause
def demo():
# reference: https://scikit-learn.org/stable/modules/classes.html#module-sklearn.cluster
# https://scikit-learn.org/stable/modules/clustering.html
pass
|
# Event: LCCS Python Fundamental Skills Workshop
# Date: May 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: A program to demonstrate how to create lists
# Lists can be created with data (each value is a list element)
boysNames = ['John', 'Jim', 'Alex', 'Fred']
girlsNames = ['Sarah', 'Alex', 'Pat', 'Mary']
favouriteSongs = ['Moondance', 'Linger', 'Stairway to Heaven']
fruits = ['Strawberry', 'Lemon', 'Orange', 'Raspberry', 'Cherry']
vehicleCount = [0, 0, 0, 0, 0, 0]
accountDetails = [1234, 'xyz', 'Alex', '1 Main Street', 827.56]
|
NL = b'\n'
DATA_SIZE = 4
FRAME_SIZE = 4
HEADER_SIZE = DATA_SIZE + FRAME_SIZE
TIMESTAMP_SIZE = 8
ATTEMPTS_SIZE = 2
MSG_ID_SIZE = 16
MSG_HEADER = TIMESTAMP_SIZE + ATTEMPTS_SIZE + MSG_ID_SIZE
|
# Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher
# qual será a base de conversão:
"""
> 1 para binário
> 2 para octal
> 3 para hexadecimal
"""
num = int(input('Escolha um número para ser convertido: '))
print('[ 1 ] Converter para BINÁRIO')
print('[ 2 ] Converter para OCTAL')
print('[ 3 ] Converter para HEXADECIMAL')
choice = int(input('Sua opção: '))
if choice == 1:
print(f'{num} convertido para BINÁRIO fica {bin(num)[2:]}!')
elif choice == 2:
print(f'{num} convertido para OCTAL fica {oct(num)[2:]}!')
elif choice == 3:
print(f'{num} convertido para HEXADECIMAL fica {hex(num)[2:]}!')
else:
print('Opção inválida, tente novamente.')
|
def run(df, docs):
for doc in docs:
doc.start("t11 - Transform Unique Id", df)
# Creates a unique id
df['nProcesso_agrupamento'] = str(df['nProcesso']) + '_' + str(df['agrupamento'])
for doc in docs:
doc.end(df)
return df
|
numbers = [9, 8, 72, 22, 21, 81, 2, 1, 11, 76, 32, 54]
def highest_num(numbers_in):
highest = numbers_in[0]
for count in range(len(numbers_in)):
if highest < numbers_in[count]:
highest = numbers_in[count]
return highest
highest_out = highest_num(numbers)
print("The highest number is", highest_out)
|
with (a, c,):
pass
with (a as b, c):
pass
async with (a, c,):
pass
async with (a as b, c):
pass
|
class FilasColumnas:
def __init__(self, nombre, filas, columnas):
self.nombre = nombre
self.filas = filas
self.columnas = columnas
def getNombre(self):
return self.nombre
def getFilas(self):
return self.filas
def getColumnas(self):
return self.filas
|
#!/usr/bin/env python
# coding: utf-8
# Write a function to which would return the greatest common of factor.
#
# <b> Input : 18, 27</b>
#
# <b> return: 9 </b>
#
#
# In[1]:
# Get the smallest of the both inputs
# Loop through the find the GCD#
def gcd(x,y):
small=min(x,y)
for i in range(1,small+1):
if(x % i == 0) and (y % i ==0):
gcd=i
return gcd
print(gcd(18,27))
# In[6]:
def gcd(x,y):
small=min(x,y)
print("x",x)
print("y",y)
print("small",small)
for i in range(1,small+1):
if x % i == 0 and y % i == 0:
print("i",i)
gcd=i
return gcd
print(gcd(18,27))
# <b>Euclidean Algorithm</b>
# In[13]:
def gcd(x,y):
while(y):
x , y = y,x % y
return x
print(gcd(18,27))
# #### Recursion
# In[12]:
def gcd(x,y):
if(y == 0):
return x
else:
return gcd(y,x % y)
print(gcd(18,27))
# In[ ]:
|
'''
现在的调查问卷越来越多了,所以出现了很多人恶意刷问卷的情况,已知某问卷需要填写名字,
如果名字仅由大小写英文字母组成且长度不超过10,则我们认为这个名字是真实有效的,否则就判定为恶意填写问卷。
请你判断出由多少有效问卷(只要名字是真实有效的,就认为问卷有效)。
'''
def wenjian(lis):
res = 0
for each in lis:
l = len(each)
if l > 10:
continue
if each.isalpha():
res += 1
print(res)
return
'''
给定一个1到N的排列P1到PN(N为偶数),初始时Pi=i(1≤i≤N),现在要对排列进行M次操作,每次操作为以下两种中一种:
①将排列的第1个数移到末尾;
②交换排列的第1个数与第2个数、第3个数与第4个数、...、第N-1个数与第N个数。
求经过这M次操作后得到的排列。
超时,草泥马的
'''
class pailei():
def __init__(self, lis1, lis2):
self.lis_ji = lis1
self.lis_ou = lis2
self.flag = 0
def do_one(self):
if self.flag == 0:
num0 = self.lis_ji.pop(0)
self.lis_ji.append(num0)
else:
num0 = self.lis_ou.pop(0)
self.lis_ou.append(num0)
self.do_two()
def do_two(self):
# i = 0
# new = [0 for _ in range(len(self.lis))]
# while (i < len(self.lis)):
# self.lis[i], self.lis[i + 1] = self.lis[i + 1], self.lis[i]
# i += 2
# self.lis = new
if self.flag == 1:
self.flag = 0
else:
self.flag = 1
def prin(self):
if self.flag == 0:
for i in range(len(self.lis_ou)):
print(self.lis_ji[i], end=' ')
print(self.lis_ou[i], end=' ')
else:
for i in range(len(self.lis_ou)):
print(self.lis_ou[i], end=' ')
print(self.lis_ji[i], end=' ')
def mai():
lie1 = input().split()
lie2 = input().split()
lis1 = [i for i in range(1, int(lie1[0]) + 1, 2)]
lis2 = [i for i in range(2, int(lie1[0]) + 1, 2)]
# print(lis1, lis2)
p = pailei(lis1, lis2)
for i in lie2:
if i == '1':
p.do_one()
elif i == '2':
p.do_two()
p.prin()
'''
在一张透明的纸上,用笔写下一个字符串。然后将纸翻面,请你判断正面和背面看到的字符串是否一样。
请注意,字符串在正反面看上去一样,必须要求每个字符是左右对称的,比如'W'字符是左右对称的,而'N'不是。
'''
def fanzhuan(str):
str2 = str[::-1]
if str != str2:
print("NO")
return
zimu = ['A', 'H', 'W', 'X', 'V', 'T', 'Y', 'U', 'M', 'I', 'O']
for i in range(len(str)):
if str[i] != str2[i]:
print('NO')
return
if str[i] not in zimu:
print('NO')
return
print('YES')
def do_fanzhuan():
while True:
try:
lie1 = input()
fanzhuan(lie1)
except:
break
'''
魔塔是一款时尚经典小游戏,我们将魔塔简化后的规则描述如下:
魔塔有n关,而你可以自由选择前往攻略哪一关,每一关只能获得一次分数。第i关攻略完成后,你将会获得ai的分数。
某些关有一个特殊的宝物,你只能在攻略完这一关的时候使用这个宝物(也可以不使用,额外的宝物并不能留到其他关卡使用),
这个宝物将使得这一关不得分,但是将你现有的总得分乘以2作为新的得分。
你现在知道了所有关卡的通关方法,也知道了每一关的得分和是否有宝物,你现在想知道,怎么选择攻略的顺序和使用宝物的方法才能让自己的得分最大化?
'''
def momtai(data_nohave, data_have):
res = 0
for i in range(len(data_nohave)):
res += data_nohave[i]
data_have.sort()
# print(data_have)
for i in range(len(data_have) - 1, -1, -1):
if data_have[i] > res:
res += data_have[i]
else:
res *= 2
print(res)
def do_motai():
num = int(input())
data_nohave = []
data_have = []
for i in range(num):
da = input().split()
if da[1] == '0':
data_nohave.append(int(da[0]))
else:
data_have.append(int(da[0]))
momtai(data_nohave, data_have)
if __name__ == '__main__':
do_motai()
|
peple = ["gilbert", "david", "richard"]
print("welcome to my parlor, " + peple[0])
print("welcome to my parlor, " + peple[1])
print("welcome to my parlor, " + peple[2])
print("richard is too stupid to come, so his not comming.")
peple = ["gilbert", "david"]
print("welcome to my parlor, " + peple[0])
print("welcome to my parlor, " + peple[1])
|
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyNvidiaMlPy(PythonPackage):
"""Python Bindings for the NVIDIA Management Library."""
homepage = "http://www.nvidia.com/"
url = "https://pypi.io/packages/source/n/nvidia-ml-py/nvidia-ml-py-11.450.51.tar.gz"
version('11.450.51', sha256='5aa6dd23a140b1ef2314eee5ca154a45397b03e68fd9ebc4f72005979f511c73')
|
# -*- coding: utf-8 -*-
"""052 - Progressão Aritmética
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1XxsY2LOjklht2ABKc1B0VXPOppV9E7Dh
"""
num = int(input('\nDigite o Primeiro número da PA: '))
razão = int(input('Digite a Razão da PA: '))
for c in range(1, 11):
print(num, end=' ')
num += razão
print('Acabou')
|
#for c in range (1, 10):
#print(c)'''
#c = 1
#while c < 11:
#print(c)
#c += 1
n = 1
par = 0
impar = 0
while n != 0:
n = int(input('digite um valor: '))
if n != 0:
if n % 2 == 0:
par += 1
else:
impar += 1
print(f'Ímpar {impar}')
print(f'Par {par}')
print('FIM')
|
BINDING_ADDRESS = ':1080' # <ADDRESS>:<PORT>
BINDING_PORT = 1080
LOCAL_CERT_FILE = './local.pem'
REMOTE_CERT_FILE = './remote.pem'
BACKLOG = 128
LOG_LEVEL = 'info'
BLOCK_SIZE = 2048 # in bytes
STAFF_BINDING_ADDRESS = '127.0.0.1'
STAFF_TCP_PORT = 32000
STAFF_UDP_PORT = 32000
STAFF_PROXY = '127.0.0.1:1080' # <ADDRESS>:<PORT>
STAFF_DNS = '8.8.8.8:53,8.8.4.4:53'
STAFF_DNS_TIMEOUT = 5.0 # in seconds
STAFF_DNS_CACHE_SIZE = 0 # max size for the local dns cache
|
def return_after_n_recursion_one(n):
return_after_n_recursion_one(n-1)
def return_after_n_recursion_two(n):
if n < 3: # Base return: identify a condition after which you will start returning
return 'Cap'
return_after_n_recursion_two(n-1)
def return_after_n_recursion(n):
if n < 3: # Base return: identify a condition after which you will start returning
return 'Cap'
return return_after_n_recursion(n-1) # recursive return
if __name__ == '__main__':
# Stack overflow
# print(return_after_n_recursion_one(5))
# return none
print(return_after_n_recursion_two(5))
# correct fucntion
print(return_after_n_recursion(5))
# recursive fucntions usually should have two returns
# inside classes while recursively looping class variables that might not be the case
|
def KadaneAlgo(alist, start, end):
#Returns (l, r, m) such that alist[l:r] is the maximum subarray in
#A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
#end.
max_ending_at_i = max_seen_so_far = alist[start]
max_left_at_i = max_left_so_far = start
# max_right_at_i is always i + 1
max_right_so_far = start + 1
for i in range(start + 1, end):
if max_ending_at_i > 0:
max_ending_at_i += alist[i]
else:
max_ending_at_i = alist[i]
max_left_at_i = i
if max_ending_at_i > max_seen_so_far:
max_seen_so_far = max_ending_at_i
max_left_so_far = max_left_at_i
max_right_so_far = i + 1
return max_left_so_far, max_right_so_far, max_seen_so_far
alist = input('Enter the elements: ')
alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = KadaneAlgo(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {}'
' and has sum {}.'.format(start, end - 1, maximum))
|
# to allow api client save environment state to database.
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
# we use cached_db backend for longlive and fast sessions.
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_COOKIE_NAME = 'sid'
SESSION_COOKIE_AGE = 86400 * 60 # 2 months. Very important to remember users.
if PRODUCTION:
SESSION_COOKIE_DOMAIN = '.{{project_name}}.com'
|
class GraphNode(object):
def __init__(self, val):
self.value = val
self.children = []
def add_child(self, new_node):
self.children.append(new_node)
def remove_child(self, del_node):
if del_node in self.children:
self.children.remove(del_node)
class Graph(object):
def __init__(self, node_list):
self.nodes = node_list
def _read_adjacent_list(self, adjacent_list):
for elem in adjacent_list:
self.nodes.add(elem[0])
self.nodes.add(elem[1])
self.add_edge(GraphNode(elem[0]), GraphNode(elem[0]))
def edge_list(self):
edge_list = list() # set give better result, but we use here 2D list
visited = set()
queue = [self.nodes[0]]
# Visit graph using BFS
while len(queue) > 0:
current_node = queue.pop(0)
visited.add(current_node)
for child in current_node.children:
# Since is an undirected graph, we check both ways
source = current_node.value
dest = child.value
if [source, dest] not in edge_list and [dest, source] not in edge_list:
edge_list.append([source, dest])
if child not in visited:
queue.append(child)
return edge_list
def adjacent_list(self):
adjacent_list = list()
visited = set()
queue = [self.nodes[0]]
# Visit graph using BFS
while len(queue) > 0:
current_node = queue.pop(0)
visited.add(current_node)
node_adjacent_list = list()
for child in current_node.children:
node_adjacent_list.append(child.value)
if child not in visited:
queue.append(child)
adjacent_list.append(node_adjacent_list)
return adjacent_list
def adjacent_matrix(self):
node_list = [node.value for node in self.nodes]
node_list.sort()
matrix = list([[0 for x in range(len(node_list))] for x in range(len(node_list))])
visited = set()
queue = [self.nodes[0]]
# Visit graph using BFS
while len(queue) > 0:
current_node = queue.pop(0)
visited.add(current_node)
for child in current_node.children:
# Since is an undirected graph, we check both ways
source_idx = node_list.index(current_node.value)
dest_idx = node_list.index(child.value)
matrix[source_idx][dest_idx] = 1
matrix[dest_idx][source_idx] = 1
if child not in visited:
queue.append(child)
return node_list, matrix
def add_edge(self, node1, node2):
if(node1 in self.nodes and node2 in self.nodes):
node1.add_child(node2)
node2.add_child(node1)
def remove_edge(self, node1, node2):
if(node1 in self.nodes and node2 in self.nodes):
node1.remove_child(node2)
node2.remove_child(node1)
def dfs_search(self, root_node, search_value):
# Sets are faster for lookups
visited = set()
# Start with a given root node
stack = [root_node]
# Repeat until the stack is empty
while len(stack) > 0:
# Pop out a node added recently
current_node = stack.pop()
# Mark it as visited
visited.add(current_node)
if current_node.value == search_value:
return current_node
# Check all the neighbours
for child in current_node.children:
# If a node hasn't been visited and is not in the stack
if (child not in visited) and (child not in stack):
stack.append(child)
def dfs_search_recursive(self, start_node, search_value):
# Set to keep track of visited nodes
visited = set()
return self.__dfs_recursion(start_node, visited, search_value)
def __dfs_recursion(self, node, visited, search_value):
if node.value == search_value:
# Don't search in other branches, if found = True
found = True
return node
visited.add(node)
found = False
result = None
# Conditional recurse on each neighbour
for child in node.children:
if (child not in visited):
result = self.__dfs_recursion(child, visited, search_value)
# Once the match is found, no more recurse
if found:
break
return result
def bfs_search(self, root_node, search_value):
# Sets are faster for lookups
visited = set()
queue = [root_node]
while len(queue) > 0:
current_node = queue.pop(0)
visited.add(current_node)
if current_node.value == search_value:
return current_node
for child in current_node.children:
if child not in visited:
queue.append(child)
# Helper functions
def print_edge(edge_list):
for edge in edge_list:
print(f" - {edge}")
def print_adjacent_list(adjacent_list):
for neighbour in adjacent_list:
print(f" - {neighbour}")
def print_adjacent_matrix(nodes, matrix):
# Print column headers
print(" " + ' '.join(map(str, nodes)))
index = 0
for row in matrix:
print(f" {nodes[index]} " + ' '.join(map(str, row)))
index += 1
# Test Cases
nodeG = GraphNode('G')
nodeR = GraphNode('R')
nodeA = GraphNode('A')
nodeP = GraphNode('P')
nodeH = GraphNode('H')
nodeS = GraphNode('S')
graph1 = Graph([nodeS,nodeH,nodeG,nodeP,nodeR,nodeA] )
graph1.add_edge(nodeG,nodeR)
graph1.add_edge(nodeA,nodeR)
graph1.add_edge(nodeA,nodeG)
graph1.add_edge(nodeR,nodeP)
graph1.add_edge(nodeH,nodeG)
graph1.add_edge(nodeH,nodeP)
graph1.add_edge(nodeS,nodeR)
# DFS Tests
print("DFS")
print(" Iterative version")
print(" Search A from S: " + "Pass" if (graph1.dfs_search(nodeS, 'A') == nodeA) else " Fail")
print(" Search S from S: " + "Pass" if (graph1.dfs_search(nodeS, 'S') == nodeS) else " Fail")
print(" Search R from S: " + "Pass" if (graph1.dfs_search(nodeS, 'R') == nodeR) else " Fail")
print(" Recoursive version")
print(" Search A from G: " + "Pass" if (graph1.dfs_search_recursive(nodeG, 'A') == nodeA) else " Fail")
print(" Search A from S: " + "Pass" if (graph1.dfs_search_recursive(nodeS, 'A') == nodeA) else " Fail")
print(" Search S from P: " + "Pass" if (graph1.dfs_search_recursive(nodeP, 'S') == nodeS) else " Fail")
print(" Search R from H: " + "Pass" if (graph1.dfs_search_recursive(nodeH, 'R') == nodeR) else " Fail")
# BFS Tests
print("BFS")
print(" Search A from S: " + "Pass" if (graph1.bfs_search(nodeS, 'A') == nodeA) else " Fail")
print(" Search S from P: " + "Pass" if (graph1.bfs_search(nodeP, 'S') == nodeS) else " Fail")
print(" Search R from H: " + "Pass" if (graph1.bfs_search(nodeH, 'R') == nodeR) else " Fail")
# Edge list tests
print("Edge list representation")
#print_edge(graph1.edge_list())
print(" Pass" if (graph1.edge_list() == [['S', 'R'], ['R', 'G'], ['R', 'A'], ['R', 'P'], ['G', 'A'], ['G', 'H'], ['P', 'H']]) else " Fail")
# Adjacent list tests
print("Adjacent list representation")
#print_adjacent_list(graph1.adjacent_list())
print(" Pass" if (graph1.adjacent_list() == [['R'], ['G', 'A', 'P', 'S'], ['R', 'A', 'H'], ['R', 'G'], ['R', 'H'], ['R', 'G'], ['G', 'P'], ['G', 'P']]) else " Fail")
# Adjacent matrix tests
print("Adjacent matrix representation")
nodes, matrix = graph1.adjacent_matrix()
#print_adjacent_matrix(nodes, matrix)
print(" Pass" if (matrix == [[0, 1, 0, 0, 1, 0], [1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0]]) else " Fail")
|
"169.Majority Element"
"""Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty
and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2"""
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return nums[len(nums)//2]
#solution 2:
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
|
x = 'Hello "Prayuth"' # Single-Quote
y = "Good Bye! 'Prayuth'" # Double-Quote
z = x + y
print(x)
print(y)
print(z)
|
# built in
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return bin(n).count('1')
# Using bit operation to cancel a 1 in each round
# Think of a number in binary n = XXXXXX1000, n - 1 is XXXXXX0111. n & (n - 1) will be XXXXXX0000
# which is just remove the last significant 1
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
c = 0
while n:
n &= n - 1
c += 1
return c
class Solution:
def hammingWeight(self, n: int) -> int:
ans=0
while n>0:
if n%2==1:
ans+=1
n=n//2
return ans
# Time: O(1)
# Space:O(1)
# use bit manipulation
def hammingWeight(self, n: int) -> int:
out = 0
while n > 0:
# n & 1 means n%2
if n & 1:
out += 1
# n>>=1 means n//2
n >>= 1
return out
|
class Solution:
def findMedianSortedArrays(self, nums1, nums2) -> float:
x = len(nums1)
y = len(nums2)
if y < x:
# Making sure nums1 is the smaller length array
return self.findMedianSortedArrays(nums2, nums1)
maxV = float('inf')
minV = float('-inf')
start, end, median = 0, x, 0
# We know
# partitionx + partitiony = (x+y+1)//2
while start <= end:
# px -> partitionx and py -> partitiony
px = start + (end - start) // 2
py = (x + y + 1) // 2 - px
# leftx, rightx -> edge elements on nums1
# lefty, righty -> edge elements on nums2
leftx, rightx, lefty, righty = 0, 0, 0, 0
leftx = minV if px == 0 else nums1[px - 1]
rightx = maxV if px == x else nums1[px]
lefty = minV if py == 0 else nums2[py - 1]
righty = maxV if py == y else nums2[py]
if leftx <= righty and lefty <= rightx:
# We found the spot for median
if (x + y) % 2 == 0:
median = (max(leftx, lefty) + min(rightx, righty)) / 2
return median
else:
median = max(leftx, lefty)
return median
elif leftx > righty:
# We are too much in the right, move towards left
end = px - 1
else:
# We are too much in the left, move towards right
start = px + 1
return -1
|
# -*- coding: utf-8 -*-
"""生成改名文件"""
def change_name_windows(name_dict, loc):
with open(loc + '\\change_name.cmd', 'w') as f:
loc = loc.replace('\\', r'\\') + r'\\'
i = 0
for key in name_dict:
i = i+1
old_name = str(key).split(r'/')[-1]
tailor = old_name.split('.')[-1]
new_name = str(i) + '-' + name_dict[key] + '.' + tailor
if(r'/' in new_name):
new_name = new_name.replace(r'/', ' ')
try:
f.write(r'ren "%s" "%s"&' % (old_name, new_name))
f.write('\n')
except:
continue
finally:
pass
f.close()
def change_name_linux(name_dict, loc):
with open(loc + '/change_name.sh', 'w') as f:
i = 0
for key in name_dict:
i = i+1
old_name = str(key).split(r'/')[-1]
tailor = old_name.split('.')[-1]
new_name = str(i) + '-' + name_dict[key] + '.' + tailor
if(r'/' in new_name):
new_name = new_name.replace(r'/', ' ')
try:
f.write(r'mv "%s" "%s"' % (old_name, new_name))
f.write('\n')
except:
continue
finally:
pass
f.close()
def get_name_dict(mp4_list, pdf_list, source_list, homework_list, exampaper_list):
name_dict = {}
for key in mp4_list:
name_dict[(key.split('/')[-1])] = mp4_list[key]
for key in pdf_list:
name_dict[(key.split('/')[-1])] = pdf_list[key]
for key in source_list:
name_dict[(key.split('/')[-1])] = source_list[key]
for key in homework_list:
name_dict[(key.split('/')[-1])] = homework_list[key]
for key in exampaper_list:
name_dict[(key.split('/')[-1])] = exampaper_list[key]
return name_dict
def change_name(mp4_list, pdf_list, source_list, homework_list, exampaper_list, loc, mode):
name_dict = get_name_dict(
mp4_list, pdf_list, source_list, homework_list, exampaper_list)
if(mode == 0):
change_name_windows(name_dict, loc)
if(mode == 1):
change_name_linux(name_dict, loc)
|
def substring_match(T, S):
"""
Simple substring matching.
O(|S| * |T - S|) Time
O(1) Space
"""
return any([T[idx:idx+len(S)] == S for idx in range(len(T) - len(S) + 1)])
"""
for idx in range(len(T) - len(S) + 1):
print(T[idx:idx + len(S)], S)
if T[idx:idx + len(S)] == S:
return True
return False
"""
if __name__=="__main__":
print("Expect True ", substring_match('hello world', 'hello'))
print("Expect True ", substring_match('hello world', 'world'))
print("Expect True ", substring_match('hello world', 'wor'))
print("Expect False ", substring_match('hello world', 'blue'))
print("Expect False ",substring_match('hello world', 'word'))
|
class BankAccount:
def __init__(self, name, number, money):
self.accountname = str(name)
self.accountnumber = int(number)
self.money = float(money)
def show(self):
msg = "Dear " + self.accountname + ", your account " + str(self.accountnumber) + " has " + str(self.money) + " remains."
print(msg)
def add(self, addamount):
self.money = self.money + addamount
print("Add successfully.")
def withdraw(self, amount):
self.money = self.money - amount
print("Withdraw successfully.")
class InterestAccount(BankAccount):
def __init__(self, ratio): #设定利率
BankAccount.__init__(self, "Em", "24680", 210.54) #在子类中直接定义母类里的属性
self.radio = float(ratio)
def ratio(self, year): #计算若干年之后的存款
self.money = self.money*(1 + self.radio)**year
myaccount = BankAccount("Oz", 13579, 120.35)
myaccount.show()
myaccount.add(100.35)
myaccount.show()
myaccount.withdraw(150.78)
myaccount.show()
youraccount = InterestAccount(0.1)
youraccount.show()
youraccount.add(100.35)
youraccount.show()
youraccount.withdraw(150.78)
youraccount.show()
youraccount.ratio(5)
youraccount.show()
|
def user_has_reporting_location(user):
sql_location = user.sql_location
if not sql_location:
return False
return not sql_location.location_type.administrative
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.