content stringlengths 7 1.05M |
|---|
class Employee:
raise_amount = 1.04
employee_Amount = 0
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@companyemail'
Employee.employee_Amount += 1
def fullname(self):
return '{} {}{}{}'.format(self.first, self.last, self.first)
def apply_raise(self):
self.pay = int(self.pay * Employee.raise_amount)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amount = amount
emp1 = Employee('herold', 'bob', 500)
print(emp1.pay)
emp1.apply_raise()
print(emp1.pay)
print(Employee.employee_Amount)
print(emp1.fullname()) |
class Editor(object):
def __init__(self):
self.color = '0 143 192'
self.visgroupshown = 1
self.visgroupautoshown = 1
def __str__(self):
out_str = 'editor\n\t\t{\n'
out_str += f'\t\t\t\"color\" \"{self.color}\"\n'
out_str += f'\t\t\t\"visgroupshown\" \"{self.visgroupshown}\"\n'
out_str += f'\t\t\t\"visgroupautoshown\" \"{self.visgroupautoshown}\"\n'
out_str += '\t\t}\n'
return out_str
|
class SharpSpringException(Exception):
pass
|
t = int(input())
for _ in range(t):
n = int(input())
s = input()
dic = {}
for i in s:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
is_yes = True
for key in dic:
if(dic[key] % 2 == 1):
is_yes = False
break
if(is_yes):
print("YES")
else:
print("NO") |
# Space: O(l)
# Time: O(m * n * l)
class Solution:
def exist(self, board, word) -> bool:
column_length = len(board)
row_length = len(board[0])
word_length = len(word)
def dfs(x, y, index):
if index >= word_length: return True
if (not 0 <= x < row_length) or (not 0 <= y < column_length): return False
if board[y][x] != word[index]: return False
temp = board[y][x]
board[y][x] = '*'
if dfs(x - 1, y, index + 1): return True
if dfs(x + 1, y, index + 1): return True
if dfs(x, y - 1, index + 1): return True
if dfs(x, y + 1, index + 1): return True
board[y][x] = temp
for column in range(column_length):
for row in range(row_length):
if dfs(row, column, 0): return True
return False
|
class User:
def __init__(self, login, password):
self._login = login
self._password = password
@property
def login(self):
return self._login
@property
def password(self):
return self._password
class Operation:
def __init__(self, a, func, b):
self._a = a
self._func = func
self._b = b
def result():
return self._func(a, b)
|
internCache = {} # XXX: upper bound on size somehow
def intern(klass, vm, method, frame):
string = frame.get_local(0)
value = string._values['value']
if value in internCache:
return internCache[value]
internCache[value] = string
return string
|
for _ in range(int(input())):
s = input().split()
for i in range(2, len(s)):
print(s[i], end=' ')
print(s[0]+' '+s[1])
|
"""
return every upper case character from a text
"""
def only_upper(string):
text = ""
for char in string:
if char.isupper():
text += char
return text
if __name__ == "__main__":
# get cipher from file if unavailable
cipher = input("paste the text here: ")
if cipher == '':
file_location = input("file location: ")
with open(file_location, encoding='utf-8') as file:
cipher = file.read()
print(only_upper(cipher))
|
"""
© https://sudipghimire.com.np
Create 2 different classes Major and Subject
create an instance of Major and add different subjects to the 'subject' attribute as a set of subjects
Create another instance for Major and add subjects to the instance
add operator overloading to add different methods so that we can create another major.
Example we have majors science, commerce
if we call
new_major = science + commerce
it should be able to return the new instance of Major with all subjects inside of them
Note:
you can try other operator overloading options too.
"""
# answer
class Subject:
def __init__(self, name) -> None:
self.name = name
def __str__(self) -> str:
return f"subject: {self.name}"
def __repr__(self) -> str:
return self.__str__()
class Major:
name = ''
def __init__(self, name) -> None:
self.name = name
self.subjects = []
def __add__(self, other: "Major"):
sub = Major(f'{self.name} + {other.name}')
sub.subjects = [*self.subjects, *other.subjects]
return sub
# Tests
sc = Major("Science")
sc.subjects.append(Subject('Physics'))
sc.subjects.append(Subject('Chemistry'))
com = Major("Commerce")
com.subjects.append(Subject('Business Mathematics'))
com.subjects.append(Subject('Accounting'))
new_major = sc + com
print(new_major.name)
print(new_major.subjects)
|
# https://stepik.org/lesson/5047/step/5?unit=1086
# Sample Input 1:
# 8
# 2
# 14
# Sample Output 1:
# 14
# 2
# 8
# Sample Input 2:
# 23
# 23
# 21
# Sample Output 2:
# 23
# 21
# 23
max, min, other = a, b, c = int(input()), int(input()), int(input())
if b > max: max, min = b, a
if c > max: max, min, other = c, a, b
if (min > other): min, other = other, min
print(max, min, other, sep='\n')
|
p=int(input("Enter the size of list : "))
l=p
x=[]
while(l):
x.append(input("Enter elements : "))
l=l-1
print(x)
while(True) :
option= int(input("Do you want to :\n1.Pop\n2Remove\n3.Exit\n4.Insert\n5.Append\n6.Search\n7.Sort\n8.Reverse\n9.DecSort ?\n"))
if(option == 1):
#POP
n=int(input("Enter the index you want to pop : "))
x.pop(n)
print(x)
elif(option == 2):
#Remove
n=(input("Enter the element you want to remove : "))
x.remove(n)
print(x)
elif(option == 3):
#Exit
exit
elif(option == 4):
#Insert
n=int(input("Enter the position : "))
value = input("Enter the element : ")
x.insert(n,value)
print(x)
elif(option == 5):
#Append
value = input("Enter the element you want to insert : ")
x.append(value)
print(x)
elif (option == 6):
#search Index
n=input("Enter the element you want to search ? ")
if x.index(n) :
print("Found at " + str(x.index(n)))
else :
print("Not Found")
elif (option == 7):
#Sort
x.sort()
print(x)
elif (option == 8):
#Reverse
x.reverse()
print(x)
elif (option == 9):
#Decending order
x=sorted(x)
x.reverse()
print(x)
|
'''
Python Code Snippets - stevepython.wordpress.com
149-Convert KMH to MPH
Source:
https://www.pythonforbeginners.com/code-snippets-source-code/
python-code-convert-kmh-to-mph/
'''
kmh = int(input("Enter km/h: "))
mph = 0.6214 * kmh
print ("Speed:", kmh, "KM/H = ", mph, "MPH")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
opticalIsomers = 2
energy = {
'CBS-QB3': GaussianLog('TS07.log'),
'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('TS07_f12.out'),
#'CCSD(T)-F12/cc-pVTZ-F12': -382.96546696009017
}
frequencies = GaussianLog('TS07freq.log')
rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[2,4], top=[4,5,6,7], symmetry=3),
HinderedRotor(scanLog=ScanLog('scan_1.log'), pivots=[2,8], top=[8,9,10,11], symmetry=3),
HinderedRotor(scanLog=ScanLog('scan_2.log'), pivots=[2,1], top=[1,12,13,14,15,16], symmetry=1),
]
|
class AdditionalInfoMeta(object):
"""Attributes that can enhance the discoverability of a resource."""
KEY = 'additionalInformation'
VALUES_KEYS = (
'categories',
'copyrightHolder',
'description',
'inLanguage',
'links',
'tags',
'updateFrequency',
'structuredMarkup',
'poseidonHash',
'providerKey',
'workExample'
)
REQUIRED_VALUES_KEYS = tuple()
class CurationMeta(object):
"""To normalize the different possible rating attributes after a curation process."""
KEY = 'curation'
VALUES_KEYS = (
"rating", "numVotes", "schema", 'isListed'
)
REQUIRED_VALUES_KEYS = {'rating', 'numVotes'}
class MetadataMain(object):
"""The main attributes that need to be included in the Asset Metadata."""
KEY = 'main'
VALUES_KEYS = {
'author',
'name',
'type',
'dateCreated',
'license',
'price',
'files'
}
REQUIRED_VALUES_KEYS = {'name', 'dateCreated', 'author', 'license', 'price', 'files'}
class Metadata(object):
"""Every Asset (dataset, algorithm, etc.) in a Nevermined Network has an associated Decentralized
Identifier (DID) and DID document / DID Descriptor Object (DDO)."""
REQUIRED_SECTIONS = {MetadataMain.KEY}
MAIN_SECTIONS = {
MetadataMain.KEY: MetadataMain,
CurationMeta.KEY: CurationMeta,
AdditionalInfoMeta.KEY: AdditionalInfoMeta
}
@staticmethod
def validate(metadata):
"""Validator of the metadata composition
:param metadata: conforming to the Metadata accepted by Nevermined, dict
:return: bool
"""
# validate required sections and their sub items
for section_key in Metadata.REQUIRED_SECTIONS:
if section_key not in metadata or not metadata[section_key] or not isinstance(
metadata[section_key], dict):
return False
section = Metadata.MAIN_SECTIONS[section_key]
section_metadata = metadata[section_key]
for subkey in section.REQUIRED_VALUES_KEYS:
if subkey not in section_metadata or section_metadata[subkey] is None:
return False
return True
|
def read_list(t): return [t(x) for x in input().split()]
def read_line(t): return t(input())
def read_lines(t, N): return [t(input()) for _ in range(N)]
for i in range(read_line(int)):
N = read_line(int)
print(min(read_list(int)) * (N-1))
|
"""
Check IRIS SystemPerformance or Caché pButtons
Extract useful details to create a performance report.
Validate common OS and IRIS/Caché configuration settings and show pass, fail
and suggested fixes.
"""
def system_check(input_file):
sp_dict = {}
with open(input_file, "r", encoding="ISO-8859-1") as file:
model_name = True
windows_info_available = False
memory_next = False
perfmon_next = False
up_counter = 0
for line in file:
# Summary
if "VMware" in line:
sp_dict["platform"] = "VMware"
if "Customer: " in line:
customer = (line.split(":")[1]).strip()
sp_dict["customer"] = customer
if "overview=" in line:
sp_dict["overview"] = (line.split("=")[1]).strip()
if "Version String: " in line or "Product Version String: " in line:
sp_dict["version string"] = (line.split(":", 1)[1]).strip()
if "Windows" in line:
sp_dict["operating system"] = "Windows"
if "Linux" in line:
sp_dict["operating system"] = "Linux"
if "AIX" in line:
sp_dict["operating system"] = "AIX"
if "Ubuntu Server LTS" in line:
sp_dict["operating system"] = "Ubuntu"
if "Profile run " in line:
sp_dict["profile run"] = line.strip()
if "Run over " in line:
sp_dict["run over"] = line.strip()
if "on machine" in line:
sp_dict[f"instance"] = (line.split(" on machine ", 1)[0]).strip()
if line.startswith("up "):
up_counter += 1
sp_dict[f"up instance {up_counter}"] = (line.split(" ", 1)[1]).strip()
# mgstat
if "numberofcpus=" in line:
sp_dict["mgstat header"] = line.strip()
mgstat_header = sp_dict["mgstat header"].split(",")
for item in mgstat_header:
if "numberofcpus" in item:
sp_dict["number cpus"] = item.split("=")[1].split(":")[0]
# Linux cpu info
if "model name :" in line:
if model_name:
model_name = False
sp_dict["processor model"] = (line.split(":")[1]).strip()
# CPF file
if "AlternateDirectory=" in line:
sp_dict["alternate journal"] = (line.split("=")[1]).strip()
if "CurrentDirectory=" in line:
sp_dict["current journal"] = (line.split("=")[1]).strip()
if "globals=" in line:
sp_dict["globals"] = (line.split("=")[1]).strip()
if "gmheap=" in line:
sp_dict["gmheap"] = (line.split("=")[1]).strip()
if "locksiz=" in line:
sp_dict["locksiz"] = (line.split("=")[1]).strip()
if "routines=" in line:
sp_dict["routines"] = (line.split("=")[1]).strip()
if "wijdir=" in line:
sp_dict["wijdir"] = (line.split("=")[1]).strip()
if "Freeze" in line:
sp_dict["freeze"] = (line.split("=")[1]).strip()
if "Asyncwij=" in line:
sp_dict["asyncwij"] = (line.split("=")[1]).strip()
if "wduseasyncio=" in line:
sp_dict["wduseasyncio"] = (line.split("=")[1]).strip()
if "jrnbufs=" in line:
sp_dict["jrnbufs"] = (line.split("=")[1]).strip()
# Linux kernel
if "kernel.hostname" in line:
sp_dict["linux hostname"] = (line.split("=")[1]).strip()
if "swappiness" in line:
sp_dict["swappiness"] = (line.split("=")[1]).strip()
# Number hugepages = shared memory. eg 48GB/2048 = 24576
if "vm.nr_hugepages" in line:
sp_dict["vm.nr_hugepages"] = (line.split("=")[1]).strip()
# Shared memory must be greater than hugepages in bytes (IRIS shared memory)
if "kernel.shmmax" in line:
sp_dict["kernel.shmmax"] = (line.split("=")[1]).strip()
if "kernel.shmall" in line:
sp_dict["kernel.shmall"] = (line.split("=")[1]).strip()
# dirty background ratio = 5
if "vm.dirty_background_ratio" in line:
sp_dict["vm.dirty_background_ratio"] = (line.split("=")[1]).strip()
# dirty ratio = 10
if "vm.dirty_ratio" in line:
sp_dict["vm.dirty_ratio"] = (line.split("=")[1]).strip()
# Linux free
if memory_next:
if "Memtotal" in line:
pass
else:
sp_dict["memory MB"] = (line.split(",")[2]).strip()
memory_next = False
if "<div id=free>" in line:
memory_next = True
# Windows info
if "Windows info" in line:
windows_info_available = True
if windows_info_available:
if "Host Name:" in line:
sp_dict["windows host name"] = (line.split(":")[1]).strip()
if "OS Name:" in line:
sp_dict["windows os name"] = (line.split(":")[1]).strip()
if "[01]: Intel64 Family" in line:
sp_dict["windows processor"] = (line.split(":")[1]).strip()
if "Time Zone:" in line:
sp_dict["windows time zone"] = line.strip()
if "Total Physical Memory:" in line:
sp_dict["windows total memory"] = (line.split(":")[1]).strip()
# if decimal point instead of comma
sp_dict["windows total memory"] = sp_dict["windows total memory"].replace(".",",")
if "hypervisor" in line:
sp_dict["windows hypervisor"] = line.strip()
# Windows perform
if perfmon_next:
sp_dict["perfmon_header"] = line.strip()
perfmon_next = False
if "beg_win_perfmon" in line:
perfmon_next = True
# # Debug
# for key in sp_dict:
# print(f"{key} : {sp_dict[key]}")
# Tidy up not found keys
if "asyncwij" not in sp_dict:
sp_dict["asyncwij"] = 0
if "wduseasyncio" not in sp_dict:
sp_dict["wduseasyncio"] = 0
if "processor model" not in sp_dict:
if "windows processor" not in sp_dict:
sp_dict["processor model"] = "Ask customer"
else:
sp_dict["processor model"] = sp_dict["windows processor"]
if "memory MB" not in sp_dict:
if "windows total memory" in sp_dict:
sp_dict['memory MB'] = int((sp_dict["windows total memory"].split(" ")[0]).replace(",", ""))
else:
sp_dict['memory MB'] = 0
return sp_dict
def build_log(sp_dict):
# Build log for cut and paste
ct_dict = {}
pass_count = warn_count = recommend_count = 0
ct_dict['swappiness'] = 5
# split up mgstat header
mgstat_header = sp_dict["mgstat header"].split(",")
for item in mgstat_header:
if "numberofcpus" in item:
sp_dict["number cpus"] = item.split("=")[1].split(":")[0]
# CPF
if "freeze" in sp_dict:
if sp_dict["freeze"] == "0":
warn_count += 1
sp_dict[
f"warning {warn_count}"] = f"Journal freeze on error is not enabled. If journal IO errors occur database activity that occurs during this period cannot be restored."
else:
pass_count += 1
sp_dict[f"pass {pass_count}"] = f"freeze on error is enabled."
if "globals" in sp_dict:
globals = sp_dict["globals"].split(",")
globals_total = 0
for item in globals:
globals_total += int(item)
sp_dict["globals total MB"] = globals_total
if "routines" in sp_dict:
routines = sp_dict["routines"].split(",")
routines_total = 0
for item in routines:
routines_total += int(item)
sp_dict["routines total MB"] = routines_total
# Linux kernel
if "swappiness" in sp_dict:
if int(sp_dict["swappiness"]) > ct_dict['swappiness']:
warn_count += 1
sp_dict[
f"warning {warn_count}"] = f"swappiness is {sp_dict['swappiness']}. For databases {ct_dict['swappiness']} is recommended to adjust how aggressive the Linux kernel swaps memory pages to disk."
else:
pass_count += 1
sp_dict[f"pass {pass_count}"] = f"swappiness is {sp_dict['swappiness']}"
# memory comes from Linux free or from Windows info
if "memory MB" in sp_dict:
huge_page_size_kb = 2048
sp_dict["memory GB"] = f"{round(int(sp_dict['memory MB']) / 1024)}"
sp_dict["shared memory MB"] = sp_dict["globals total MB"] + sp_dict["routines total MB"] + round(
int(sp_dict['gmheap']) / 1024)
sp_dict[
"shared memory calc"] = f"globals {sp_dict['globals total MB']} MB + routines {sp_dict['routines total MB']} MB + gmheap {round(int(sp_dict['gmheap']) / 1024)} MB"
sp_dict["75pct memory MB"] = round(int(sp_dict['memory MB']) * .75)
sp_dict["75pct memory number huge pages"] = round((sp_dict["75pct memory MB"] * 1024) / huge_page_size_kb)
if "vm.nr_hugepages" in sp_dict:
if int(sp_dict["vm.nr_hugepages"]) == 0:
warn_count += 1
sp_dict[
f"warning {warn_count}"] = f"Hugepages not set. For performance, memory efficiency and to protect the shared memory from paging out, use huge page memory space. It is not advisable to specify HugePages much higher than the shared memory amount because the unused memory are not be available to other components."
recommend_count += 1
sp_dict[
f"recommend {recommend_count}"] = f"Set HugePages, see IRIS documentation: https://docs.intersystems.com/irislatest/csp/docbook/Doc.View.cls?KEY=GCI_prepare_install#GCI_memory_big_linux"
recommend_count += 1
msg = (
f"Total memory is {int(sp_dict['memory MB']):,} MB, 75% of total memory is {int(sp_dict['75pct memory MB']):,} MB."
)
sp_dict[
f"recommend {recommend_count}"] = msg
recommend_count += 1
msg = (
f"Shared memory (globals+routines+gmheap) is {sp_dict['shared memory MB']:,} MB. "
f"({round((sp_dict['shared memory MB'] / int(sp_dict['memory MB'])) * 100):,}% of total memory)."
)
sp_dict[
f"recommend {recommend_count}"] = msg
recommend_count += 1
shared_memory_plus_5pct = round(sp_dict['shared memory MB'] * 1.05)
msg = (
f"Number of HugePages for {huge_page_size_kb} KB page size for ({sp_dict['shared memory MB']:,} MB + 5% buffer = {shared_memory_plus_5pct:,} MB) "
f"is {round((shared_memory_plus_5pct * 1024) / huge_page_size_kb)}"
)
sp_dict[
f"recommend {recommend_count}"] = msg
else:
sp_dict["hugepages MB"] = round(int(sp_dict["vm.nr_hugepages"]) * huge_page_size_kb / 1024)
if sp_dict["hugepages MB"] < sp_dict["shared memory MB"]:
warn_count += 1
sp_dict[
f"warning {warn_count}"] = f"shared memory is {sp_dict['shared memory MB']:,} MB hugepages is {sp_dict['hugepages MB']:,} MB"
else:
pass_count += 1
sp_dict[f"pass {pass_count}"] = f"HugePages is set:"
pass_count += 1
msg = (
f"Total memory is {int(sp_dict['memory MB']):,} MB. "
)
sp_dict[
f"pass {pass_count}"] = msg
pass_count += 1
msg = (
f"75% of total memory is {int(sp_dict['75pct memory MB']):,} MB. "
f"Shared memory is {sp_dict['shared memory MB']:,}, {round(sp_dict['shared memory MB'] / int(sp_dict['memory MB']) * 100):,}% of total memory."
)
sp_dict[
f"pass {pass_count}"] = msg
pass_count += 1
msg = (
f"Shared memory (globals+routines+gmheap) is {sp_dict['shared memory MB']:,} MB, hugepages is {sp_dict['hugepages MB']:,} MB, "
f"gap is {sp_dict['hugepages MB'] - sp_dict['shared memory MB']:,} MB. "
f"Shared memory is {round((sp_dict['shared memory MB']) / int(sp_dict['hugepages MB']) * 100):,}% of huge pages."
)
sp_dict[
f"pass {pass_count}"] = msg
if "kernel.shmmax" in sp_dict:
if int(sp_dict["kernel.shmmax"]) == 18446744073692774399:
pass_count += 1
sp_dict[f"pass {pass_count}"] = f"Kernel shared memory limit is at default"
else:
if "hugepages MB" in sp_dict:
if int(sp_dict["kernel.shmmax"]) < sp_dict["hugepages MB"] * 1024 * 1024:
warn_count += 1
sp_dict[f"warning {warn_count}"] = f"Kernel shared memory limit must be higher than hugepages."
else:
pass_count += 1
sp_dict[f"pass {pass_count}"] = f"Kernel shared memory limit is higher than hugepages"
if "vm.dirty_background_ratio" in sp_dict:
if int(sp_dict["vm.dirty_background_ratio"]) > 5:
warn_count += 1
sp_dict[
f"warning {warn_count}"] = f"dirty_background_ratio is {sp_dict['vm.dirty_background_ratio']}. InterSystems recommends setting this parameter to 5. This setting is the maximum percentage of active memory that can be filled with dirty pages before pdflush begins to write them."
else:
pass_count += 1
sp_dict[f"pass {pass_count}"] = f"dirty_background_ratio is {sp_dict['vm.dirty_background_ratio']}"
if "vm.dirty_ratio" in sp_dict:
if int(sp_dict["vm.dirty_ratio"]) > 10:
warn_count += 1
sp_dict[
f"warning {warn_count}"] = f"dirty_ratio is {sp_dict['vm.dirty_ratio']}. InterSystems recommends setting this parameter to 10. This setting is the maximum percentage of total memory that can be filled with dirty pages before processes are forced to write dirty buffers themselves during their time slice instead of being allowed to do more writes. These changes force the Linux pdflush daemon to write out dirty pages more often rather than queue large amounts of updates that can potentially flood the storage with a large burst of updates"
else:
pass_count += 1
sp_dict[f"pass {pass_count}"] = f"dirty_ratio is {sp_dict['vm.dirty_ratio']}"
# Debug
# for key in sp_dict:
# print(f"{key} : {sp_dict[key]}")
# Some tidy up if empty
if "platform" not in sp_dict:
sp_dict["platform"] = "N/A"
if 'shared memory calc' not in sp_dict:
sp_dict['shared memory calc'] = ""
if 'shared memory MB' not in sp_dict:
sp_dict['shared memory MB'] = 0
hostname = "N/A"
if 'linux hostname' in sp_dict:
hostname = sp_dict['linux hostname']
if 'windows host name' in sp_dict:
hostname = sp_dict['windows host name']
# Build log
log = f"\nSystem Summary for {sp_dict['customer']}\n\n"
log += f"Hostname : {hostname}\n"
log += f"Instance : {sp_dict['instance']}\n"
log += f"Operating system : {sp_dict['operating system']}\n"
log += f"Platform : {sp_dict['platform']}\n"
log += f"CPUs : {sp_dict['number cpus']}\n"
log += f"Processor model : {sp_dict['processor model']}\n"
log += f"Memory : {sp_dict['memory GB']} GB\n"
log += f"Shared memory : {sp_dict['shared memory calc']} = {int(sp_dict['shared memory MB']):,} MB\n"
log += f"Version : {sp_dict['version string']}\n"
log += f"Date collected : {sp_dict['profile run']}\n"
first_pass = True
for key in sp_dict:
if "pass" in key:
if first_pass:
log += "\nPasses:\n"
first_pass = False
log += f"- {sp_dict[key]}\n"
first_warning = True
for key in sp_dict:
if "warn" in key:
if first_warning:
log += "\nWarnings:\n"
first_warning = False
log += f"- {sp_dict[key]}\n"
recommendations_count = False
log += "\nRecommendations:\n"
if not first_warning:
log += f"- Review and fix warnings above\n"
for key in sp_dict:
if "recommend" in key:
recommendations_count = True
log += f"- {sp_dict[key]}\n"
if not recommendations_count and first_warning:
log += f"- No recommendations\n"
first_instance = True
for key in sp_dict:
if "up instance" in key:
if first_instance:
log += "\nAll instances on this host:\n"
first_instance = False
log += f"- {sp_dict[key]}\n"
return log
|
#assert True == True
def mean(num_list):
try:
mean = sum(num_list)/float(len(num_list))
if isinstance(mean, complex):
return NotImplemented
return mean
except ZeroDivisionError as detail:
msg = "\nCannot compute the mean value of an empty list."
raise ZeroDivisionError(detail.__str__()+ msg)
except TypeError as detail:
msg = "\nPlease pass a list of numbers not strings"
raise TypeError(detail.__str__()+ msg)
|
# Сообщения пользователю
ERROR_LOGGING = 'Update "%s" caused error "%s"'
LOGGING = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
PASSED = 'Экзамен сдан! Количество правильных ответов: '
FAILED = 'Экзамен не сдан! Возможно тебе стоит потренироваться (/training)\n' \
'Количество правильных ответов: '
EXAM_STARTED = 'Экзамен начался! Удачи!'
# Команды
WELCOME = 'Добро пожаловать в тренажёр ПДД! 👮\n\n' \
'Здесь ты можешь тренировать свои знания в двум режимах:\n' \
'1. Режим тренировки (/training). После каждого вопроса\n' \
'ты узнаешь правильный ответ и комментарий к вопросу. \n' \
'2. Режим Экзамена (/exam). Тебе будет задано 20 вопросов.\n' \
'В конце ты узнаешь количество набранных баллов и результат экзамена\n\n' \
'База вопросов постоянно обновляется.'
# Кнопки бота
ONE = '1️⃣'
TWO = '2️⃣'
THREE = '3️⃣'
FOUR = '4️⃣'
MENU = 'Вернуться в меню'
SOS = 'Комментарий к вопросу'
NEXT = 'Следующий вопрос️'
AGAIN = 'Пересдать экзамен'
|
def solution(clothes):
style = dict()
for i in clothes:
if i[1] not in style:
style[i[1]]=1
else :
style[i[1]]+=1
print(style)
answer =1
for i in style.values():
answer*=(i+1)
return answer-1 |
# tunnels at level = 0
#https://www.openstreetmap.org/way/167952621
assert_has_feature(
18, 41903, 101298, "roads",
{"kind": "highway", "highway": "motorway", "id": 167952621,
"name": "Presidio Pkwy.", "is_tunnel": True, "sort_key": 331})
# http://www.openstreetmap.org/way/89912879
assert_has_feature(
16, 19829, 24234, "roads",
{"kind": "major_road", "highway": "trunk", "id": 89912879,
"name": "Sullivan Square Underpass", "is_tunnel": True, "sort_key": 329})
#https://www.openstreetmap.org/way/117837633
assert_has_feature(
18, 67234, 97737, "roads",
{"kind": "major_road", "highway": "primary", "id": 117837633,
"name": "Dixie Hwy.", "is_tunnel": True, "sort_key": 328})
#https://www.openstreetmap.org/way/57782075
assert_has_feature(
18, 67251, 97566, "roads",
{"kind": "major_road", "highway": "secondary", "id": 57782075,
"name": "S Halsted St.", "is_tunnel": True, "sort_key": 327})
#https://www.openstreetmap.org/way/57708079
assert_has_feature(
18, 67255, 97547, "roads",
{"kind": "major_road", "highway": "tertiary", "id": 57708079,
"name": "W 74th St.", "is_tunnel": True, "sort_key": 326})
#https://www.openstreetmap.org/way/56393654
assert_has_feature(
18, 67233, 97449, "roads",
{"kind": "minor_road", "highway": "residential", "id": 56393654,
"name": "S Paulina St.", "is_tunnel": True, "sort_key": 310})
#https://www.openstreetmap.org/way/190835369
assert_has_feature(
18, 67258, 97452, "roads",
{"kind": "minor_road", "highway": "service", "id": 190835369,
"name": "S Wong Pkwy.", "is_tunnel": True, "sort_key": 308})
|
'''
Kattis - rijeci
from fibo(0) = 0, fibo(1) = 1, output the x-1th and xth fibo numbers, x <= 45
Simply use a for loop.
Time: O(x), Space: O(1)
'''
x = int(input())
a = 1
b = 0
for i in range(x):
a, b = b, a+b
print(a, b) |
"""
Sujet: NSI DS1 - Partie C : Problème 1
Nom: Charrier
Prénom: Max
Date: 7/10/2021
"""
def tiragePhotos(n):
if n < 50:
return 0.2 * n
elif n >= 100 and n < 100:
return 0.15 * n
elif n >= 100:
return 0.1 * n
print(tiragePhotos(10))
|
"""This module contains class Task for represent single task entity,
class TaskStatus"""
class TaskStatus:
OPENED = 'opened'
SOLVED = 'solved'
ACTIVATED = 'activated'
FAILED = 'failed'
class RelatedTaskType:
"""
This class defines constants which using in related tasks
"""
BLOCKER = 'blocker'
CONTROLLER = 'controller'
class Task:
"""
This class defines single task entity attributes
"""
def __init__(self, name, key, queue=None, description=None, parent=None,
related=None, author=None, responsible: list=None, priority=0,
progress=0, start=None, deadline=None, tags=None,
reminder=None, creating_time=None):
self.name = name
self.queue = queue
self.description = description
self.parent = parent
self.sub_tasks = []
self.related = related
self.author = author
self.priority = priority
self.progress = progress
self.start = start
self.deadline = deadline
self.tags = tags
self.reminder = reminder
self.status = TaskStatus.OPENED
self.key = key
self.creating_time = creating_time
self.editing_time = creating_time
if responsible is None:
self.responsible = []
else:
self.responsible = responsible
|
# 1st solution
# O(1) time | O(1) space
class Solution:
def bitwiseComplement(self, n: int) -> int:
k = 1
while k < n:
k = (k << 1) | 1
return k - n |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2019 Lorenzo
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.
"""
__all__ = (
"PokemonException",
"PokeAPIException",
"RateLimited",
"NotFound",
"Forbidden",
"NoMoreItems"
)
class PokemonException(Exception):
"""The base exception for this wrapper."""
class PokeAPIException(PokemonException):
"""Exception raised when an HTTP request is not successful.
Attributes
----------
response: :class:`aiohttp.ClientResponse`
The failed HTTP response.
status: :class:`int`
The HTTP status code.
message: :class:`str`
A, hopefully, useful exception message."""
def __init__(self, response, message: str):
self.response = response
self.status = response.status
self.message = "API responded with status code {0} {2}: {1}".format(self.status, message, response.reason)
super().__init__(self.message)
class RateLimited(PokeAPIException):
"""Exception raised when an HTTP request is equal to 429 TOO MANY REQUESTS.
This exception will only raise if you surpass 100 requests per minutes,
if you need more requests then that it would be better to host your own
API instance.
This inherits from :exc:`PokeAPIException`."""
class NotFound(PokeAPIException):
"""Exception raised when an HTTP request response code is equal to 404 NOT FOUND.
This inherits from :exc:`PokeAPIException`."""
class Forbidden(PokeAPIException):
"""Exception raised when an HTTP request response code is equal to 403 FORBIDDEN.
This inherits from :exc:`PokeAPIException`."""
class NoMoreItems(PokemonException):
"""Exception raised when an AsyncIterator is empty.
This is usually catched to stop the iteration, unless you directly use
the :meth:`AsyncPaginationIterator.next` method you shouldn't worry about it too much.
.. versionadded:: 0.1.0a"""
|
"""
https://leetcode.com/problems/find-smallest-letter-greater-than-target/
Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target.
Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.
Examples:
Input:
letters = ["c", "f", "j"]
target = "a"
Output: "c"
Input:
letters = ["c", "f", "j"]
target = "c"
Output: "f"
Input:
letters = ["c", "f", "j"]
target = "d"
Output: "f"
Input:
letters = ["c", "f", "j"]
target = "g"
Output: "j"
Input:
letters = ["c", "f", "j"]
target = "j"
Output: "c"
Input:
letters = ["c", "f", "j"]
target = "k"
Output: "c"
Note:
letters has a length in range [2, 10000].
letters consists of lowercase letters, and contains at least 2 unique letters.
target is a lowercase letter.
"""
# time complexity: O(n), space complexity: O(1)
class Solution:
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
if target < letters[0]:
return letters[0]
elif target >= letters[-1]:
return letters[0]
else:
# letter[0] <= target < letter[-1]
for i in range(len(letters) - 1):
if letters[i] <= target < letters[i + 1]:
return letters[i + 1]
|
"""88. Lowest Common Ancestor of a Binary Tree
Assume two nodes are exist in tree."""
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return the least common ancestor(LCA) of the two nodes.
"""
def lowestCommonAncestor(self, root, A, B):
# write your code here
### Practice:
return self.dfs(root, A, B)
def dfs(self, node, a, b):
if not node:
return None
if node == a or node == b:
return node
left = self.dfs(node.left)
right = self.dfs(node.right)
if not left and not right:
return None
if left and right:
return node
return left or right
##
if not root:
return None
if root == A or root == B:
return root
left = self.lowestCommonAncestor(root.left, A, B)
right = self.lowestCommonAncestor(root.right, A, B)
if left and right:
return root
if left or right:
return left or right
return None
|
"""
Configuration for defining the datastore.
"""
MAX_KEY_LEN = 32 # characters
MAX_VALUE_SIZE = 16 * 1024 # 16 Kbytes
MAX_LOCAL_STORAGE_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB
LOCAL_STORAGE_PREPEND_PATH = "/tmp" # this will be prepended to the file path provided
|
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November',
'December']
for n in range(1, 12, 1):
n = int(input())
print(months[n - 1])
break |
def add_mod(x: int, y: int, modulo: int = 32) -> int:
"""
Modular addition
:param x:
:param y:
:param modulo:
:return:
"""
return (x + y) & ((1 << modulo) - 1)
def left_circ_shift(x: int, shift: int, n_bits: int) -> int:
"""
Does a left binary circular shift on the number x of n_bits bits
:param x: A number
:param shift: The number of bits to shift
:param n_bits: The number of bits of x
:return: The shifted result
"""
mask = (1 << n_bits) - 1 # Trick to create a ones mask of n bits
x_base = (x << shift) & mask # Keep it in the n_bits range
return x_base | (x >> (n_bits - shift)) # Add the out of bounds bits
def right_circ_shift(x: int, shift: int, n_bits: int) -> int:
"""
Does a right binary circular shift on the number x of n_bits bits
:param x: A number
:param shift: The number of bits to shift
:param n_bits: The number of bits of x
:return: The shifted result
"""
mask = (1 << n_bits) - 1 # Trick to create a ones mask of n bits
x_base = x >> shift
return x_base | (x << (n_bits - shift) & mask)
def merge_bytes(payload_list: list) -> int:
"""
Gives an 8 bytes value from a byte list
:param payload_list: Byte list (max size is 8)
:return:
"""
while len(payload_list) < 8:
payload_list.append(0x00)
result = payload_list[0]
for i in range(1, 8):
result = (result << 8) | payload_list[i]
return result
def split_bytes(payload: int) -> bytearray:
"""
Gives a byte list of an 8 bytes value
:param payload: The 8 bytes value
:return:
"""
payload_list = bytearray()
for i in range(8):
payload_list.insert(0, (payload >> (8 * i)) & 0xFF) # Extract bytes by shifting right and masking
return payload_list
|
# Utility class used for string processing
def HasText(line, values):
retval = False
found = 0
for data in values:
if data in line:
found += 1
if found == len(values):
retval = True
return retval
def TextAfter(line, values):
retval = ""
if HasText(line, values):
loc = 0
for data in values:
end = line.find(data, 0) + len(data)
if end > loc:
loc = end
retval = line[loc+1:]
return retval
|
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
hash_table = {}
longest_length = 0
for i in range(len(s)):
if hash_table.get(s[i]):
cur_length = len(hash_table.keys())
if cur_length > longest_length:
longest_length = cur_length
new_hash_table = {
s[i]: i
}
# 复制旧hash表中的非重复部分到新hash表中
for key in hash_table.keys():
if hash_table.get(key) > hash_table.get(s[i]):
new_hash_table[key] = hash_table.get(key)
hash_table = new_hash_table
else:
# 记录该字符出现的索引
hash_table[s[i]] = i
last_length = len(hash_table.keys())
if last_length > longest_length:
longest_length = last_length
return longest_length
s = Solution()
print(s.lengthOfLongestSubstring("abcabcbb"))
print(s.lengthOfLongestSubstring("bbbbb"))
print(s.lengthOfLongestSubstring("pwwkew"))
print(s.lengthOfLongestSubstring(" "))
print(s.lengthOfLongestSubstring("dvdf"))
|
# razbi n, ki je 5000 mestno stevilo na 100 50 mestnih stevilk in najdi prvih 10 stevk vsote teh 100-tih stevil
sez = [37107287533902102798797998220837590246510135740250,46376937677490009712648124896970078050417018260538,74324986199524741059474233309513058123726617309629,91942213363574161572522430563301811072406154908250,23067588207539346171171980310421047513778063246676,89261670696623633820136378418383684178734361726757,28112879812849979408065481931592621691275889832738,44274228917432520321923589422876796487670272189318,47451445736001306439091167216856844588711603153276,70386486105843025439939619828917593665686757934951,62176457141856560629502157223196586755079324193331,64906352462741904929101432445813822663347944758178,92575867718337217661963751590579239728245598838407,58203565325359399008402633568948830189458628227828,80181199384826282014278194139940567587151170094390,35398664372827112653829987240784473053190104293586,86515506006295864861532075273371959191420517255829,71693888707715466499115593487603532921714970056938,54370070576826684624621495650076471787294438377604,53282654108756828443191190634694037855217779295145,36123272525000296071075082563815656710885258350721,45876576172410976447339110607218265236877223636045,17423706905851860660448207621209813287860733969412,81142660418086830619328460811191061556940512689692,51934325451728388641918047049293215058642563049483,62467221648435076201727918039944693004732956340691,15732444386908125794514089057706229429197107928209,55037687525678773091862540744969844508330393682126,18336384825330154686196124348767681297534375946515,80386287592878490201521685554828717201219257766954,78182833757993103614740356856449095527097864797581,16726320100436897842553539920931837441497806860984,48403098129077791799088218795327364475675590848030,87086987551392711854517078544161852424320693150332,59959406895756536782107074926966537676326235447210,69793950679652694742597709739166693763042633987085,41052684708299085211399427365734116182760315001271,65378607361501080857009149939512557028198746004375,35829035317434717326932123578154982629742552737307,94953759765105305946966067683156574377167401875275,88902802571733229619176668713819931811048770190271,25267680276078003013678680992525463401061632866526,36270218540497705585629946580636237993140746255962,24074486908231174977792365466257246923322810917141,91430288197103288597806669760892938638285025333403,34413065578016127815921815005561868836468420090470,23053081172816430487623791969842487255036638784583,11487696932154902810424020138335124462181441773470,63783299490636259666498587618221225225512486764533,67720186971698544312419572409913959008952310058822,95548255300263520781532296796249481641953868218774,76085327132285723110424803456124867697064507995236,37774242535411291684276865538926205024910326572967,23701913275725675285653248258265463092207058596522,29798860272258331913126375147341994889534765745501,18495701454879288984856827726077713721403798879715,38298203783031473527721580348144513491373226651381,34829543829199918180278916522431027392251122869539,40957953066405232632538044100059654939159879593635,29746152185502371307642255121183693803580388584903,41698116222072977186158236678424689157993532961922,62467957194401269043877107275048102390895523597457,23189706772547915061505504953922979530901129967519,86188088225875314529584099251203829009407770775672,11306739708304724483816533873502340845647058077308,82959174767140363198008187129011875491310547126581,97623331044818386269515456334926366572897563400500,42846280183517070527831839425882145521227251250327,55121603546981200581762165212827652751691296897789,32238195734329339946437501907836945765883352399886,75506164965184775180738168837861091527357929701337,62177842752192623401942399639168044983993173312731,32924185707147349566916674687634660915035914677504,99518671430235219628894890102423325116913619626622,73267460800591547471830798392868535206946944540724,76841822524674417161514036427982273348055556214818,97142617910342598647204516893989422179826088076852,87783646182799346313767754307809363333018982642090,10848802521674670883215120185883543223812876952786,71329612474782464538636993009049310363619763878039,62184073572399794223406235393808339651327408011116,66627891981488087797941876876144230030984490851411,60661826293682836764744779239180335110989069790714,85786944089552990653640447425576083659976645795096,66024396409905389607120198219976047599490197230297,64913982680032973156037120041377903785566085089252,16730939319872750275468906903707539413042652315011,94809377245048795150954100921645863754710598436791,78639167021187492431995700641917969777599028300699,15368713711936614952811305876380278410754449733078,40789923115535562561142322423255033685442488917353,44889911501440648020369068063960672322193204149535,41503128880339536053299340368006977710650566631954,81234880673210146739058568557934581403627822703280,82616570773948327592232845941706525094512325230608,22918802058777319719839450180888072429661980811197,77158542502016545090413245809786882778948721859617,72107838435069186155435662884062257473692284509516,20849603980134001723930671666823555245252804609722,53503534226472524250874054075591789781264330331690]
def prva_deset_mestna(sez):
vsota = sum(sez)
return int(str(vsota)[:10])
print(prva_deset_mestna(sez))
5537376230 |
"""
Represents the domain of a variable, i.e. the possible values that each
variable may assign.
"""
class Domain:
# ==================================================================
# Constructors
# ==================================================================
def __init__ ( self, value_or_values ):
self.values = []
if type( value_or_values ) is int:
self.values.append( value_or_values )
else:
self.values = value_or_values
self.modified = False
def copy ( self, values ):
self.values = values
# ==================================================================
# Accessors
# ==================================================================
# Checks if value exists within the domain
def contains ( self, v ):
return v in self.values
# Returns number of values in the domain
def size ( self ):
return len(self.values)
# Returns true if no values are contained in the domain
def isEmpty ( self ):
return not self.values
# Returns whether or not the domain has been modified
def isModified ( self ):
return self.modified
# ==================================================================
# Modifiers
# ==================================================================
# Adds a value to the domain
def add ( self, num ):
if num not in self.values:
self.values.append( num )
# Remove a value from the domain
def remove ( self, num ):
if num in self.values:
self.modified = True
self.values.remove( num )
return True
else:
return False
# Sets the modified flag
def setModified ( self, modified ):
self.modified = modified
# ==================================================================
# String representation
# ==================================================================
def __str__ ( self ):
output = "{"
for i in range(len(self.values) - 1):
output += str(self.values[i]) + ", "
try:
output += str(self.values[-1])
except:
pass
output += "}"
return output
|
# Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50.
print('Os números PARES que estão no intervalo entre 1 e 50 são: ')
for c in range(2, 51, 2):
print('.', end='')
print(c, end=' ')
print('Acabou...')
|
"""
approximations using histograms
"""
class Interval:
def __init__(self, low, up):
if low > up:
raise Exception("Cannot create interval: low must be smaller or equal than up")
self.low = low
self.up = up
def __len__(self):
return self.up - self.low
def contains(self, c):
return self.low <= c <= self.up
def intersect(self, interval):
if interval.low > self.up or self.low > interval.up:
return None
return Interval(max(self.low, interval.low), min(self.up, interval.up))
class Histogram:
def __init__(self):
self.intervals = []
def add_interval(self, low, up, elements):
"""
Adds a new bucket to the histogram.
:param low: lower bound
:param up: upper bound
:param elements: number of elements
:return: self
"""
self.intervals.append((Interval(low, up), elements))
return self
def approx_equals_constant_verbose(histogram, c):
numerator = []
denominator = [elements for _, elements in histogram.intervals]
for interval, elements in histogram.intervals:
if interval.contains(c):
numerator.append(elements)
result = sum(numerator) / sum(denominator)
return f'\\frac{{ {" + ".join(map(str, numerator))} }}{{ {" + ".join(map(str, denominator))} }} = {result:.4f}', result
def approx_greater_constant_verbose(histogram, c):
numerator_tex = []
numerator = []
denominator = [elements for _, elements in histogram.intervals]
for interval, elements in histogram.intervals:
if interval.contains(c):
numerator_tex.append(f'\\frac{{ {interval.up} - {c} }}{{ {interval.up} - {interval.low} }} \\cdot {elements}')
numerator.append(((interval.up - c) / len(interval)) * elements)
elif interval.low > c:
numerator_tex.append(f'{elements}')
numerator.append(elements)
result = sum(numerator) / sum(denominator)
return f'\\frac{{ {" + ".join(numerator_tex)} }}{{ {" + ".join(map(str, denominator))} }} = {result:.4f}', result
def approx_join_verbose(hist1, hist2):
numerator_tex = []
numerator = []
denominator_h1 = [elements for _, elements in hist1.intervals]
denominator_h2 = [elements for _, elements in hist2.intervals]
for i1, elements1 in hist1.intervals:
for i2, elements2 in hist2.intervals:
iprime = i1.intersect(i2)
if iprime is None:
continue
numerator_tex.append(
f'\\frac{{ {len(iprime)} }}{{ {len(i1)} }} \\cdot {elements1} \\cdot '
f'\\frac{{ {len(iprime)} }}{{ {len(i2)} }} \\cdot {elements2}'
)
numerator.append(((len(iprime) / len(i1)) * elements1) * ((len(iprime) / len(i2)) * elements2))
result = sum(numerator) / (sum(denominator_h1) * sum(denominator_h2))
return f'\\frac{{ {" + ".join(numerator_tex)} }}' \
f'{{ \\left( {" + ".join(map(str, denominator_h1))} \\right) \\cdot ' \
f'\\left( {" + ".join(map(str, denominator_h2))} \\right) }} '\
f' = {result:.4f}', result
|
async def run(plugin, ctx, channel):
plugin.db.configs.update(ctx.guild.id, "message_logging", True)
plugin.db.configs.update(ctx.guild.id, "message_log_channel", f"{channel.id}")
await ctx.send(plugin.t(ctx.guild, "enabled_module_channel", _emote="YES", module="Message Logging", channel=channel.mention)) |
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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.
"""Exception Class for proliantutils module."""
class ProliantUtilsException(Exception):
"""Parent class for all Proliantutils exceptions."""
pass
class InvalidInputError(Exception):
message = "Invalid Input: %(reason)s"
class IloError(ProliantUtilsException):
"""Base Exception.
This exception is used when a problem is encountered in
executing an operation on the iLO.
"""
def __init__(self, message, errorcode=None):
super(IloError, self).__init__(message)
class IloClientInternalError(IloError):
"""Internal Error from IloClient.
This exception is raised when iLO client library fails to
communicate properly with the iLO.
"""
def __init__(self, message, errorcode=None):
super(IloError, self).__init__(message)
class IloCommandNotSupportedError(IloError):
"""Command not supported on the platform.
This exception is raised when iLO client library fails to
communicate properly with the iLO
"""
def __init__(self, message, errorcode=None):
super(IloError, self).__init__(message)
class IloLoginFailError(IloError):
"""iLO Login Failed.
This exception is used to communicate a login failure to
the caller.
"""
messages = ['User login name was not found',
'Login failed', 'Login credentials rejected']
statuses = [0x005f, 0x000a]
message = 'Authorization Failed'
def __init__(self, message, errorcode=None):
super(IloError, self).__init__(message)
class IloConnectionError(IloError):
"""Cannot connect to iLO.
This exception is used to communicate an HTTP connection
error from the iLO to the caller.
"""
def __init__(self, message):
super(IloConnectionError, self).__init__(message)
# This is not merged with generic InvalidInputError because
# of backward-compatibility reasons. If we changed this,
# use-cases of excepting 'IloError' to catch 'IloInvalidInputError'
# will be broken.
class IloInvalidInputError(IloError):
"""Invalid Input passed.
This exception is used when invalid inputs are passed to
the APIs exposed by this module.
"""
def __init__(self, message):
super(IloInvalidInputError, self).__init__(message)
class HPSSAException(ProliantUtilsException):
message = "An exception occured in hpssa module"
def __init__(self, message=None, **kwargs):
if not message:
message = self.message
message = message % kwargs
super(HPSSAException, self).__init__(message)
class PhysicalDisksNotFoundError(HPSSAException):
message = ("Not enough physical disks were found to create logical disk "
"of size %(size_gb)s GB and raid level %(raid_level)s")
class HPSSAOperationError(HPSSAException):
message = ("An error was encountered while doing hpssa configuration: "
"%(reason)s.")
|
def exist(board, word):
"""
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell,
where "adjacent" cells are those horizontally or vertically neighboring.
The same letter cell may not be used more than once.
:param board:
:param word:
:return:
"""
if not board:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if helper(board, i, j, word):
return True
return False
def helper(board, word, i, j): # Recursive process for DFS search
if len(word) == 1: # Reach the end, return True
return True
for next_start in [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]]:
board[i][j] = None
if 0 <= next_start[0] < len(board) and 0 <= next_start[1] < len(board[0]):
if board[next_start[0]][next_start[1]] == word[1]:
if helper(board, word[1:], next_start[0], next_start[1]):
return True
board[i][j] = word[0]
return False
|
class TwoSum:
def __init__(self):
"""
Initialize your data structure here.
"""
self.numberCount = defaultdict(int)
def add(self, number: int) -> None:
"""
Add the number to an internal data structure..
"""
self.numberCount[number] += 1
def find(self, value: int) -> bool:
"""
Find if there exists any pair of numbers which sum is equal to the value.
"""
for number in self.numberCount.keys():
complementNumber = value - number
if complementNumber == number:
if self.numberCount[number] > 1:
return True
else:
if complementNumber in self.numberCount:
return True
return False
# Your TwoSum object will be instantiated and called as such:
# obj = TwoSum()
# obj.add(number)
# param_2 = obj.find(value) |
### --- ### --- ### --- ###
#! While structure:
#` 1. The while statement starts with the while keyword, followed bu a test condition, and ends with a colon (:).
#` 2. The loop body contains the code that gets repeated at each step of the loop. Each line is indented four spaces.
#$ Example:
n = 10
while n < 20:
print(n)
n = n + 1
#. infinite loop
while n <= 10:
print(n)
|
class Solution:
def maxScore(self, s: str) -> int:
"""String.
Running time: O(n) where n == len(s).
"""
res = 0
ones = 0
for i in s:
if i == '1':
ones += 1
z, o = 0, 0
for i in s[:-1]:
if i == '0':
z += 1
else:
o += 1
res = max(res, z + ones - o)
return res
|
class EndpointSolver(object):
def __init__(self, env, charms):
self.env = env
self.charms = charms
# Relation endpoint match logic
def solve(self, ep_a, ep_b):
service_a, charm_a, endpoints_a = self._parse_endpoints(ep_a)
service_b, charm_b, endpoints_b = self._parse_endpoints(ep_b)
pairs = self._select_endpoint_pairs(endpoints_a, endpoints_b)
return service_a, service_b, pairs
return service_a, pairs[0], service_b, pairs[1]
def _check_endpoints_match(self, ep_a, ep_b):
if ep_a['interface'] != ep_b['interface']:
return False
if ep_a['role'] == 'requirer' and ep_b['role'] == 'provider':
return True
elif ep_a['role'] == 'provider' and ep_b['role'] == 'requirer':
return True
elif ep_a['role'] == 'peer' and ep_b['role'] == 'peer':
if ep_a['service'] == ep_b['service']:
return True
return False
def _select_endpoint_pairs(self, eps_a, eps_b):
pairs = []
for ep_a in eps_a:
for ep_b in eps_b:
if self._check_endpoints_match(ep_a, ep_b):
scope = 'global'
if (ep_a['scope'] == 'container' or
ep_b['scope'] == 'container'):
scope = 'container'
pairs.append((ep_a, ep_b, scope))
return pairs
def _parse_endpoints(self, descriptor):
if ':' in descriptor:
svc_name, rel_name = descriptor.split(u":")
else:
svc_name, rel_name = unicode(descriptor), None
svc = self.env.env_get_service(svc_name)
charm = self.charms.get(svc.charm_url)
endpoints = []
found = False
for ep in charm.endpoints:
ep['service'] = svc_name
if rel_name:
if ep['name'] == rel_name:
found = True
endpoints.append(ep)
break
else:
endpoints.append(ep)
if rel_name and not found:
raise EnvError({'Error': '%s rel endpoint not valid' % descriptor})
return svc, charm, endpoints
|
# -*- encoding: utf-8 -*-
def _single_action_str(self):
return '/'.join(list(iter(self)))
def _multi_action_str(_):
cmd_actions = [
str(arg) for arg in [
RUN_OPT_NAME,
STOP_OPT_NAME,
ENABLE_OPTS_NAME,
ENABLE_OPTS_NAME,
]
]
return ', '.join(cmd_actions)
frozenset_single_action_opts = type(
'frozenset_argv_action_opts',
(frozenset,),
{'__str__': _single_action_str},
)
frozenset_multiple_action_opts = type(
'frozenset_argv_action_opts',
(frozenset,),
{'__str__': _multi_action_str},
)
RUN_OPT_NAME = 'run'
START_OPT_NAME = 'start'
STOP_OPT_NAME = 'stop'
ENABLE_OPT_NAME = 'en'
ENABLE_OPT_NAME_ALIAS = 'enable'
ENABLE_OPTS_NAME = frozenset_single_action_opts(
{ENABLE_OPT_NAME, ENABLE_OPT_NAME_ALIAS},
)
DISABLE_OPT_NAME = 'dis'
DISABLE_OPT_NAME_ALIAS = 'disable'
DISABLE_OPTS_NAME = frozenset_single_action_opts(
{DISABLE_OPT_NAME, DISABLE_OPT_NAME_ALIAS},
)
ARGS_ACTION_OPTS = frozenset_multiple_action_opts(
{RUN_OPT_NAME} | {STOP_OPT_NAME} | ENABLE_OPTS_NAME | DISABLE_OPTS_NAME,
)
ALL = 'all'
|
'''
Pomodoro Timer code There are six steps in the original technique:
Decide on the task to be done.
Set the pomodoro timer (traditionally to 25 minutes).[1]
Work on the task.
End work when the timer rings and put a checkmark on a piece of paper.[5]
If you have fewer than four checkmarks, take a short break (3–5 minutes), then go to step 2.
After four pomodoros, take a longer break (15–30 minutes), reset your checkmark count to zero, then go to step 1.
''' |
# -------------------------------------------------------- #
# Linguagens de Programação - Prof. Flavio Varejão - 2019-1
# Segundo trabalho de implementação
#
# Aluno: Rafael Belmock Pedruzzi
#
# trabIO.py: módulo responsável pelo tratamento de I/O dos arquivos:
# entrada.txt, distancia.txt, result.txt e saida.txt
# -------------------------------------------------------- #
# Função para leitura dos arquivos entrada.txt e distancia.txt
# retorno: a distância limite e uma lista contendo listas que representam cada ponto lido (a posição na lista indica a linha que foi lido).
def read_Entry():
# Abrindo arquivo distancia.txt para obter a distância limite:
f = open("./distancia.txt", "r")
dist = float(f.read())
f.close()
# Abrindo arquivo entrada.txt para obter os pontos:
points = [] # lista de pontos.
f = open("./entrada.txt", "r")
for line in f.readlines():
points.append([float(x) for x in line.split()])
f.close()
return dist, points
# Funcão para impressão do arquivo saida.txt
# parâmetros: a lista de grupos.
# pós-condição: lista inalterada inalterada.
def print_Groups(g):
# Criando arquivo de escrita:
saida = open("saida.txt", "w")
# Imprimindo cada grupo. Somente os identifiicadores são impressos, em ordem cressente e separados por espaços. grupos diferentes são separados por uma linha em branco.
for i in range(len(g)):
if i != 0:
saida.write("\n\n")
for j in range(len(g[i])):
if j != 0:
saida.write(" ")
saida.write(str(g[i][j]))
# Fechando arquivo:
saida.close
# Funcão para impressão do arquivo result.txt
# parâmetros: valor da SSE do agrupamento.
def print_SSE(sse):
# Criando arquivo de escrita:
saida = open("result.txt", "w")
# Imprimindo a SSE:
saida.write('{0:.{1}f}'.format(sse, 4))
saida.close |
rosha = bet_log[-1]
bet_log = []
|
#
# PySNMP MIB module CISCO-LWAPP-REAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-REAP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:49:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection")
cLApSysMacAddress, = mibBuilder.importSymbols("CISCO-LWAPP-AP-MIB", "cLApSysMacAddress")
cLWlanIndex, = mibBuilder.importSymbols("CISCO-LWAPP-WLAN-MIB", "cLWlanIndex")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Unsigned32, Counter32, Gauge32, IpAddress, Counter64, Integer32, MibIdentifier, iso, ObjectIdentity, Bits, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Unsigned32", "Counter32", "Gauge32", "IpAddress", "Counter64", "Integer32", "MibIdentifier", "iso", "ObjectIdentity", "Bits", "NotificationType", "TimeTicks")
TextualConvention, RowStatus, TruthValue, StorageType, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "TruthValue", "StorageType", "DisplayString")
ciscoLwappReapMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 517))
ciscoLwappReapMIB.setRevisions(('2010-10-06 00:00', '2010-02-06 00:00', '2007-11-01 00:00', '2007-04-19 00:00', '2006-04-19 00:00',))
if mibBuilder.loadTexts: ciscoLwappReapMIB.setLastUpdated('201010060000Z')
if mibBuilder.loadTexts: ciscoLwappReapMIB.setOrganization('Cisco Systems Inc.')
ciscoLwappReapMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 0))
ciscoLwappReapMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1))
ciscoLwappReapMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2))
ciscoLwappReapWlanConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1))
ciscoLwappReapApConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2))
ciscoLwappReapGroupConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3))
cLReapWlanConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1), )
if mibBuilder.loadTexts: cLReapWlanConfigTable.setStatus('current')
cLReapWlanConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-WLAN-MIB", "cLWlanIndex"))
if mibBuilder.loadTexts: cLReapWlanConfigEntry.setStatus('current')
cLReapWlanEnLocalSwitching = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapWlanEnLocalSwitching.setStatus('current')
cLReapWlanClientIpLearnEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 2), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapWlanClientIpLearnEnable.setStatus('current')
cLReapWlanApAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapWlanApAuth.setStatus('current')
cLReapApConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1), )
if mibBuilder.loadTexts: cLReapApConfigTable.setStatus('current')
cLReapApConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-AP-MIB", "cLApSysMacAddress"))
if mibBuilder.loadTexts: cLReapApConfigEntry.setStatus('current')
cLReapApNativeVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4095)).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapApNativeVlanId.setStatus('current')
cLReapApVlanEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapApVlanEnable.setStatus('current')
cLReapHomeApEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapHomeApEnable.setStatus('current')
cLReapApLeastLatencyJoinEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 4), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapApLeastLatencyJoinEnable.setStatus('current')
cLReapHomeApLocalSsidReset = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 5), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapHomeApLocalSsidReset.setStatus('current')
cLReapApVlanIdTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2), )
if mibBuilder.loadTexts: cLReapApVlanIdTable.setStatus('current')
cLReapApVlanIdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2, 1), ).setIndexNames((0, "CISCO-LWAPP-AP-MIB", "cLApSysMacAddress"), (0, "CISCO-LWAPP-WLAN-MIB", "cLWlanIndex"))
if mibBuilder.loadTexts: cLReapApVlanIdEntry.setStatus('current')
cLReapApVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4095)).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cLReapApVlanId.setStatus('current')
cLReapGroupConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1), )
if mibBuilder.loadTexts: cLReapGroupConfigTable.setStatus('current')
cLReapGroupConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-REAP-MIB", "cLReapGroupName"))
if mibBuilder.loadTexts: cLReapGroupConfigEntry.setStatus('current')
cLReapGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 1), SnmpAdminString())
if mibBuilder.loadTexts: cLReapGroupName.setStatus('current')
cLReapGroupPrimaryRadiusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 2), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupPrimaryRadiusIndex.setStatus('current')
cLReapGroupSecondaryRadiusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 3), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupSecondaryRadiusIndex.setStatus('current')
cLReapGroupStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 4), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupStorageType.setStatus('current')
cLReapGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRowStatus.setStatus('current')
cLReapGroupRadiusPacTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 6), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(2, 4095)).clone(10)).setUnits('days').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusPacTimeout.setStatus('deprecated')
cLReapGroupRadiusAuthorityId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusAuthorityId.setStatus('current')
cLReapGroupRadiusAuthorityInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusAuthorityInfo.setStatus('current')
cLReapGroupRadiusServerKey = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 9), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)).clone('****')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusServerKey.setStatus('current')
cLReapGroupRadiusIgnoreKey = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 10), TruthValue().clone('true')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusIgnoreKey.setStatus('current')
cLReapGroupRadiusEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 11), TruthValue().clone('false')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusEnable.setStatus('current')
cLReapGroupRadiusLeapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 12), TruthValue().clone('false')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusLeapEnable.setStatus('current')
cLReapGroupRadiusEapFastEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 13), TruthValue().clone('false')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusEapFastEnable.setStatus('current')
cLReapGroupRadiusPacTimeoutCtrl = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 14), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095)).clone(10)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupRadiusPacTimeoutCtrl.setStatus('current')
cLReapGroupApConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2), )
if mibBuilder.loadTexts: cLReapGroupApConfigTable.setStatus('current')
cLReapGroupApConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1), ).setIndexNames((0, "CISCO-LWAPP-REAP-MIB", "cLReapGroupName"), (0, "CISCO-LWAPP-AP-MIB", "cLApSysMacAddress"))
if mibBuilder.loadTexts: cLReapGroupApConfigEntry.setStatus('current')
cLReapGroupApStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1, 1), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupApStorageType.setStatus('current')
cLReapGroupApRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1, 2), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupApRowStatus.setStatus('current')
cLReapGroupUserConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3), )
if mibBuilder.loadTexts: cLReapGroupUserConfigTable.setStatus('current')
cLReapGroupUserConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1), ).setIndexNames((0, "CISCO-LWAPP-REAP-MIB", "cLReapGroupName"), (0, "CISCO-LWAPP-REAP-MIB", "cLReapGroupUserName"))
if mibBuilder.loadTexts: cLReapGroupUserConfigEntry.setStatus('current')
cLReapGroupUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 24)))
if mibBuilder.loadTexts: cLReapGroupUserName.setStatus('current')
cLReapGroupUserPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupUserPassword.setStatus('current')
cLReapGroupUserStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 3), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupUserStorageType.setStatus('current')
cLReapGroupUserRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cLReapGroupUserRowStatus.setStatus('current')
ciscoLwappReapMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1))
ciscoLwappReapMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2))
ciscoLwappReapMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 1)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapMIBCompliance = ciscoLwappReapMIBCompliance.setStatus('deprecated')
ciscoLwappReapMIBComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 2)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapMIBComplianceRev1 = ciscoLwappReapMIBComplianceRev1.setStatus('deprecated')
ciscoLwappReapMIBComplianceRev2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 3)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapMIBComplianceRev2 = ciscoLwappReapMIBComplianceRev2.setStatus('deprecated')
ciscoLwappReapMIBComplianceRev3 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 4)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigRadiusGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigUserAuthGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroupHomeAp"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapMIBComplianceRev3 = ciscoLwappReapMIBComplianceRev3.setStatus('deprecated')
ciscoLwappReapMIBComplianceRev4 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 5)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigUserAuthGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroupHomeAp"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigRadiusGroup1"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapMIBComplianceRev4 = ciscoLwappReapMIBComplianceRev4.setStatus('deprecated')
ciscoLwappReapMIBComplianceRev5 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 6)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigUserAuthGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroupHomeAp"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigRadiusGroup1"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroupSup1"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapMIBComplianceRev5 = ciscoLwappReapMIBComplianceRev5.setStatus('current')
ciscoLwappReapWlanConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 1)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapWlanEnLocalSwitching"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapWlanConfigGroup = ciscoLwappReapWlanConfigGroup.setStatus('current')
ciscoLwappReapApConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 2)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapApNativeVlanId"), ("CISCO-LWAPP-REAP-MIB", "cLReapApVlanId"), ("CISCO-LWAPP-REAP-MIB", "cLReapApVlanEnable"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapApConfigGroup = ciscoLwappReapApConfigGroup.setStatus('current')
ciscoLwappReapGroupConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 3)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapGroupPrimaryRadiusIndex"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupSecondaryRadiusIndex"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupStorageType"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRowStatus"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupApStorageType"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupApRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapGroupConfigGroup = ciscoLwappReapGroupConfigGroup.setStatus('current')
ciscoLwappReapGroupConfigRadiusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 4)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusPacTimeout"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusAuthorityId"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusAuthorityInfo"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusServerKey"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusIgnoreKey"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusLeapEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusEapFastEnable"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapGroupConfigRadiusGroup = ciscoLwappReapGroupConfigRadiusGroup.setStatus('deprecated')
ciscoLwappReapGroupConfigUserAuthGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 5)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapGroupUserPassword"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupUserStorageType"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupUserRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapGroupConfigUserAuthGroup = ciscoLwappReapGroupConfigUserAuthGroup.setStatus('current')
ciscoLwappReapApConfigGroupHomeAp = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 6)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapHomeApEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapApLeastLatencyJoinEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapWlanClientIpLearnEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapHomeApLocalSsidReset"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapApConfigGroupHomeAp = ciscoLwappReapApConfigGroupHomeAp.setStatus('current')
ciscoLwappReapGroupConfigRadiusGroup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 7)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusAuthorityId"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusAuthorityInfo"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusServerKey"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusIgnoreKey"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusLeapEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusEapFastEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusPacTimeoutCtrl"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapGroupConfigRadiusGroup1 = ciscoLwappReapGroupConfigRadiusGroup1.setStatus('current')
ciscoLwappReapWlanConfigGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 8)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapWlanApAuth"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoLwappReapWlanConfigGroupSup1 = ciscoLwappReapWlanConfigGroupSup1.setStatus('current')
mibBuilder.exportSymbols("CISCO-LWAPP-REAP-MIB", cLReapGroupRadiusIgnoreKey=cLReapGroupRadiusIgnoreKey, cLReapGroupUserName=cLReapGroupUserName, cLReapApNativeVlanId=cLReapApNativeVlanId, cLReapWlanEnLocalSwitching=cLReapWlanEnLocalSwitching, cLReapGroupRadiusEnable=cLReapGroupRadiusEnable, cLReapGroupUserStorageType=cLReapGroupUserStorageType, ciscoLwappReapMIBComplianceRev1=ciscoLwappReapMIBComplianceRev1, cLReapGroupName=cLReapGroupName, ciscoLwappReapApConfig=ciscoLwappReapApConfig, cLReapApConfigEntry=cLReapApConfigEntry, cLReapGroupRadiusPacTimeout=cLReapGroupRadiusPacTimeout, cLReapApVlanId=cLReapApVlanId, cLReapGroupUserConfigEntry=cLReapGroupUserConfigEntry, cLReapGroupApRowStatus=cLReapGroupApRowStatus, PYSNMP_MODULE_ID=ciscoLwappReapMIB, ciscoLwappReapMIBComplianceRev4=ciscoLwappReapMIBComplianceRev4, ciscoLwappReapWlanConfigGroup=ciscoLwappReapWlanConfigGroup, ciscoLwappReapGroupConfigUserAuthGroup=ciscoLwappReapGroupConfigUserAuthGroup, ciscoLwappReapGroupConfigRadiusGroup1=ciscoLwappReapGroupConfigRadiusGroup1, cLReapGroupRadiusPacTimeoutCtrl=cLReapGroupRadiusPacTimeoutCtrl, cLReapGroupApConfigTable=cLReapGroupApConfigTable, cLReapWlanClientIpLearnEnable=cLReapWlanClientIpLearnEnable, cLReapApVlanIdTable=cLReapApVlanIdTable, cLReapGroupApConfigEntry=cLReapGroupApConfigEntry, cLReapGroupRadiusEapFastEnable=cLReapGroupRadiusEapFastEnable, cLReapGroupUserRowStatus=cLReapGroupUserRowStatus, cLReapApConfigTable=cLReapApConfigTable, ciscoLwappReapMIBGroups=ciscoLwappReapMIBGroups, cLReapGroupRadiusAuthorityId=cLReapGroupRadiusAuthorityId, ciscoLwappReapGroupConfigGroup=ciscoLwappReapGroupConfigGroup, cLReapWlanConfigTable=cLReapWlanConfigTable, cLReapHomeApEnable=cLReapHomeApEnable, cLReapGroupConfigTable=cLReapGroupConfigTable, ciscoLwappReapApConfigGroupHomeAp=ciscoLwappReapApConfigGroupHomeAp, cLReapGroupRadiusLeapEnable=cLReapGroupRadiusLeapEnable, ciscoLwappReapMIBNotifs=ciscoLwappReapMIBNotifs, cLReapApVlanIdEntry=cLReapApVlanIdEntry, cLReapGroupRadiusServerKey=cLReapGroupRadiusServerKey, ciscoLwappReapApConfigGroup=ciscoLwappReapApConfigGroup, cLReapWlanConfigEntry=cLReapWlanConfigEntry, cLReapGroupSecondaryRadiusIndex=cLReapGroupSecondaryRadiusIndex, ciscoLwappReapMIBObjects=ciscoLwappReapMIBObjects, cLReapHomeApLocalSsidReset=cLReapHomeApLocalSsidReset, ciscoLwappReapMIBComplianceRev2=ciscoLwappReapMIBComplianceRev2, ciscoLwappReapMIBComplianceRev5=ciscoLwappReapMIBComplianceRev5, ciscoLwappReapMIBConform=ciscoLwappReapMIBConform, cLReapGroupPrimaryRadiusIndex=cLReapGroupPrimaryRadiusIndex, ciscoLwappReapWlanConfigGroupSup1=ciscoLwappReapWlanConfigGroupSup1, cLReapGroupUserConfigTable=cLReapGroupUserConfigTable, cLReapGroupStorageType=cLReapGroupStorageType, ciscoLwappReapGroupConfigRadiusGroup=ciscoLwappReapGroupConfigRadiusGroup, ciscoLwappReapGroupConfig=ciscoLwappReapGroupConfig, cLReapApLeastLatencyJoinEnable=cLReapApLeastLatencyJoinEnable, ciscoLwappReapMIB=ciscoLwappReapMIB, cLReapWlanApAuth=cLReapWlanApAuth, ciscoLwappReapMIBCompliances=ciscoLwappReapMIBCompliances, cLReapGroupConfigEntry=cLReapGroupConfigEntry, ciscoLwappReapWlanConfig=ciscoLwappReapWlanConfig, ciscoLwappReapMIBCompliance=ciscoLwappReapMIBCompliance, cLReapGroupRowStatus=cLReapGroupRowStatus, cLReapGroupApStorageType=cLReapGroupApStorageType, cLReapGroupUserPassword=cLReapGroupUserPassword, ciscoLwappReapMIBComplianceRev3=ciscoLwappReapMIBComplianceRev3, cLReapApVlanEnable=cLReapApVlanEnable, cLReapGroupRadiusAuthorityInfo=cLReapGroupRadiusAuthorityInfo)
|
number = 15
while True:
number += 1
last_digit = str(number)[-1:]
if last_digit != '6':
continue
small = int(number / 10)
large = int('6' + str(small))
if large % number == 0:
print('--')
print(str(number) + ' || ' + str(small) + ' : ' + str(large))
print('Division: ' + str(int(large / number)))
if int(large / number) == 4:
print('Answer: ' + str(number))
break
|
fake_users_db = {
"typo11": {
"username": "typo11",
"full_name": "Tammy Cacablanka",
"email": "tammy@localhost.com",
"disabled": False,
"hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"
},
"typo12": {
"username": "typo12",
"full_name": "Sammy Cacablanka",
"email": "master@localhost.com",
"disabled": True,
"hashed_password": "fakehashedsecret2"
}
}
|
"""
DSC20 WI22 HW05
Name: William Trang
PID: A16679845
"""
# begin helper methods
def ceil(x):
"""
Simulation to math.ceil
No doctest needed
"""
if int(x) != x:
return int(x) + 1
return int(x)
def log(x):
"""
Simulation to math.log with base e
No doctests needed
"""
n = 1e10
return n * ((x ** (1/n)) - 1)
# end helper methods
# Question1
def db_calc(dynamic, inst_mult):
"""
Given a musical dynamic abbreviation as a string and a
multiplier inst_mult for louder and softer instruments
as a float, compute the intial decibel level based on
distance from the instrument.
Parameters:
dynamic: Abbreviation of music dynamic.
inst_mult: Multiplier for louder/softer instruments.
Returns:
Function that computes intial decibel level of
instrument for a given distance.
>>> snare_1 = db_calc('ff', 1.2)
>>> snare_1(0)
126
>>> snare_1(10)
80
>>> snare_1(50)
48
>>> db_calc('loud', 1)(35)
Traceback (most recent call last):
...
AssertionError
>>> db_calc('pp', 1.200001)(50)
Traceback (most recent call last):
...
AssertionError
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> snare_2 = db_calc('p', 1.3)
Traceback (most recent call last):
...
AssertionError
>>> snare_3 = db_calc('pp', 1)
>>> snare_3(10)
0
>>> snare_4 = db_calc('pp', 'cha')
Traceback (most recent call last):
...
AssertionError
"""
assert isinstance(dynamic, str)
assert isinstance(inst_mult, (float, int))
assert (inst_mult >= .8) and (inst_mult <= 1.2)
db = {'pp': 30,
'p': 45,
'mp': 60,
'mf': 75,
'f': 90,
'ff': 105}
assert dynamic in db
db_init = db[dynamic] * inst_mult
def db_level(distance):
"""
Computes the observed decibel level given
a distance away from the instrument.
Parameters:
distance: Distance away from the instrument as an integer.
Returns:
Decibel level for given distance from instrument as an integer.
"""
assert isinstance(distance, int)
assert distance >= 0
if distance == 0:
return round(db_init)
level = db_init - 20 * log(distance)
if level < 0:
return 0
return round(level)
return db_level
# Question2
def next_move(file_names, decision):
"""
Takes in a filepath containing constestant names and decisions,
and a final decision to make. Returns a message for the
contestants whose decisions match the final decisions.
Parameters:
file_names: Path to file containing names and decisions.
decision: Final decision that determines which contestants
are sent messages.
Returns:
Function that creates message for contestants
that match the final decision.
>>> message_to_students = next_move("files/names.txt", "h")
>>> mess = message_to_students("Never give up!")
>>> print(mess)
Dear I!
Unfortunately, it is time to go home. Never give up!
>>> message_to_students = next_move("files/names.txt", "s")
>>> mess = message_to_students("San Diego, Earth.")
>>> print(mess)
Dear A, C, E, G, K!
We are happy to announce that you can move to the next round.
It will be held at San Diego, Earth.
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> message_2 = next_move('files/names2.txt', 'h')
>>> mess2 = message_2('It is all good.')
>>> print(mess2)
Dear Will, M!
Unfortunately, it is time to go home. It is all good.
>>> message_2 = next_move('files/names2.txt', 's')
>>> mess2 = message_2('Yay!')
>>> print(mess2)
Dear Zhi!
We are happy to announce that you can move to the next round.
It will be held at Yay!
>>> mess2 = message_2('MOS114')
>>> print(mess2)
Dear Zhi!
We are happy to announce that you can move to the next round.
It will be held at MOS114
"""
f_name = 0
dec_index = 3
name_list = []
tmp = ''
with open(file_names, 'r') as f:
for line in f:
tmp = line.split(',')
if tmp[dec_index].strip().lower() == decision.lower():
name_list.append(tmp[f_name])
def final_message(message):
"""
Creates and returns a string final_message based
on an inputted message.
Parameters:
message: Custom message to send to participants
matching the decision.
Returns:
A predetermined string message along with the custom
message to send.
"""
output_str = 'Dear ' + ', '.join(name_list) + '!\n'
if decision == 's':
output_str += 'We are happy to announce that you can \
move to the next round.\nIt will be held at \
' + message
else:
output_str += 'Unfortunately, it is time to go home. ' + message
return output_str
return final_message
# Question3
def forge(filepath):
"""
Reads a given filepath containing names and votes
with votes being 1 and 0, and changes people's votes
in the file to make the majority vote what is desired.
Parameters:
filepath: Path to file containing names and votes.
Returns:
Function that forges votes in the file.
>>> forge('files/vote1.txt')(0)
>>> with open('files/vote1.txt', 'r') as outfile1:
... print(outfile1.read().strip())
Jerry,0
Larry,0
Colin,0
Scott,0
Jianming,0
Huaning,1
Amy,1
Elvy,1
>>> forge('files/vote2.txt')(0)
>>> with open('files/vote2.txt', 'r') as outfile2:
... print(outfile2.read().strip())
Jerry,0
Larry,0
Colin,0
Scott,1
Jianming,0
Huaning,1
Amy,1
Elvy,0
>>> forge('files/vote3.txt')(1)
>>> with open('files/vote3.txt', 'r') as outfile3:
... print(outfile3.read().strip())
Jerry,1
Larry,1
Colin,1
Scott,0
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> forge('files/vote4.txt')(1)
>>> with open('files/vote4.txt', 'r') as outfile4:
... print(outfile4.read().strip())
Will,1
Zhi,1
TL,1
DJ,0
Rj,0
RD,1
>>> forge('files/vote5.txt')(0)
>>> with open('files/vote5.txt', 'r') as outfile5:
... print(outfile5.read().strip())
Will,0
Zhi,0
TL,1
DJ,0
Rj,0
RD,1
>>> forge('files/vote6.txt')(1)
>>> with open('files/vote6.txt', 'r') as outfile6:
... print(outfile6.read().strip())
Will,1
"""
votes = {0: 0,
1: 0}
vote_index = 1
name_index = 0
with open(filepath, 'r') as f:
for line in f:
votes[int(line.split(',')[vote_index])] += 1
majority = int((votes[0] + votes[1]) / 2) + 1
def change_votes(wanted):
"""
Takes in a vote that is the desired result of the
voting process. Write to the file to make the wanted
vote the majority vote.
Parameters:
wanted: The desired majority in the voting process.
"""
votes_to_change = majority - votes[wanted]
new_votes = ''
with open(filepath, 'r') as f:
for line in f:
if votes_to_change > 0:
if int(line.split(',')[vote_index]) != int(wanted):
new_votes += line.split(',')[name_index] + \
',' + str(wanted) + '\n'
votes_to_change -= 1
else:
new_votes += line
else:
new_votes += line
with open(filepath, 'w') as f:
f.write(new_votes)
return change_votes
# Question4.1
def number_of_adults_1(lst, age = 18):
"""
Takes in a list of integers containing ages
and an age threshold, and returns the number of
adults needed to supervise people below the
age threshold. Each adult can supervise three people.
Parameters:
lst: List containing ages of people as integers.
age: Age threshold where people no longer need
supervision. Default value is 18.
Returns:
Number of adults needed to supervise people under
the age threshold.
>>> number_of_adults_1([1,2,3,4,5,6,7])
3
>>> number_of_adults_1([1,2,3,4,5,6,7], 5)
2
>>> number_of_adults_1([1,2,3,4,5,6,7], age = 2)
1
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> number_of_adults_1([18, 20, 19, 90])
0
>>> number_of_adults_1([1,2,3,4,5,6,7], 2)
1
>>> number_of_adults_1([])
0
"""
adults_per_kid = 3
return ceil(len([ages for ages in lst if ages < age]) / adults_per_kid)
# Question4.2
def number_of_adults_2(*args):
"""
Takes in positional arguments of integer ages,
and returns the number of adults needed to supervise
people below the age threshold which is 18. One adult
can supervise three people.
Parameters:
*args: Positional arguments that designate age.
Returns:
Number of adults needed to supervise people below
eighteen years old.
>>> number_of_adults_2(1,2,3,4,5,6,7)
3
>>> number_of_adults_2(10,20,13,4)
1
>>> number_of_adults_2(19, 20)
0
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> number_of_adults_2(1,2,3,4,5,6,7,8,9,10,19)
4
>>> number_of_adults_2(10)
1
>>> number_of_adults_2(0)
1
"""
adults_per_kid = 3
age_threshold = 18
return ceil(len([ages for ages in args \
if ages < age_threshold]) / adults_per_kid)
# Question4.3
def number_of_adults_3(*args, age = 18):
"""
Takes in positional arguments of integer ages,
and returns the number of adults needed to supervise
people below the given age threshold. One adult
can supervise three people.
Parameters:
*args: Positional arguments that designate age.
age: Age threshold where people no longer need
supervision. Default value is 18.
Returns:
Number of adults needed to supervise people below
age threshold.
>>> number_of_adults_3(1,2,3,4,5,6,7)
3
>>> number_of_adults_3(1,2,3,4,5,6,7, age = 5)
2
>>> number_of_adults_3(1,2,3,4,5,6,7, age = 2)
1
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> number_of_adults_3(19,19,20,20,31)
0
>>> number_of_adults_3(1,2,3,4,5,6,7, 5)
3
>>> number_of_adults_3(19,20,21, age = 42)
1
"""
adults_per_kid = 3
return ceil(len([ages for ages in args if ages < age]) / adults_per_kid)
# Question5
def school_trip(age_limit, **kwargs):
"""
Given a set of keyword arguments with key being each class and
the values being ages in the class, return a dictionary where
keys are classes and values are the number of adults needed to
supervise the people in the class. Kids below the age limit need
supervision and adults can supervise up to 3 kids.
Parameters:
age_limit: Age threshold where people no longer need supervision.
**kwargs: Keyword arguments where key is class and values
are a list of ages in the class.
Returns:
Dictionary where keys are classes and values are number of adults
needed to supervise the class.
>>> school_trip(14, class1=[1,2,3], class2 =[4,5,6,7], class3=[15,16])
{'class1': 1, 'class2': 2, 'class3': 0}
>>> school_trip(14, class1=[21,3], class2 =[41,1,2,24,6], class3=[30,3,1,7,88])
{'class1': 1, 'class2': 1, 'class3': 1}
>>> school_trip(100, class1=[21,3], class2 =[41,1000,2,24,6], class3=[3,1,7,88])
{'class1': 1, 'class2': 2, 'class3': 2}
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> school_trip(2, class2=[2,2,2], class3=[3,3,3,3,3,3,3], class4=[4,4,4])
{'class2': 0, 'class3': 0, 'class4': 0}
>>> school_trip(11, class1=[12,13,14,15], class2=[10,10,10,11])
{'class1': 0, 'class2': 1}
>>> school_trip(15, class1=[12,13,14,15], \
class2=[10,10,10,11,12,13,14,14,14,14])
{'class1': 1, 'class2': 4}
"""
trip = []
for keys, values in kwargs.items():
trip.append((keys, number_of_adults_3(*values, age = age_limit)))
return dict(trip)
# Question6
def rearrange_args(*args, **kwargs):
"""
Given positional arguments and keyword arguments, return a list
of tuples containing the type of argument and number of the
argument as well as its value.
Parameters:
*args: Random positional arguments.
**kwargs: Random keyword arguments.
Returns:
List of tuples where the first value of the tuple is the
type of argument with its number and the second value is
the value of the argument. Keyword arguments' first value
also contains the key of the keyword argument.
>>> rearrange_args(10, False, player1=[25, 30], player2=[5, 50])
[('positional_0', 10), ('positional_1', False), \
('keyword_0_player1', [25, 30]), ('keyword_1_player2', [5, 50])]
>>> rearrange_args('L', 'A', 'N', 'G', L='O', I='S')
[('positional_0', 'L'), ('positional_1', 'A'), ('positional_2', 'N'), \
('positional_3', 'G'), ('keyword_0_L', 'O'), ('keyword_1_I', 'S')]
>>> rearrange_args(no_positional=True)
[('keyword_0_no_positional', True)]
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> rearrange_args(11, 'no_kw')
[('positional_0', 11), ('positional_1', 'no_kw')]
>>> rearrange_args(11, keyW = 'MONKEY!!!!')
[('positional_0', 11), ('keyword_0_keyW', 'MONKEY!!!!')]
>>> rearrange_args(keyW = 4.0, d11='C')
[('keyword_0_keyW', 4.0), ('keyword_1_d11', 'C')]
"""
key_index = 0
val_index = 1
return [('positional_' + str(count), arg) for count, arg\
in list(enumerate(args))] + [('keyword_' + str(num) + '_' + \
str(dic[key_index]), dic[val_index]) \
for num, dic in enumerate(kwargs.items())]
|
# Aidan Conlon - 27 March 2019
# This is the solution to Problem 6
# Write a program that takes a user input string and outputs every second word.
UserInput = input("Please enter a string of text:") # Print to screen the comment and take a value entered by the user.
for i, word in enumerate(UserInput.split()): # Use a for loop to pull each word from the sentence using a split function
if i %2 == 0: # if i is divisible by 2 with no carry then it is the 1st, 3rd, 5th word etc. in the entered sentence.
print("%s" % (word), sep=' ', end=' ') # Print the string given the value of word (for this iteration of i), usng concatenation of each word seperated by a space
quit() # Quit the program
|
# THIS IS STATIC
WEEKDAYS = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Friday",
5: "Saturday",
6: "Sunday"
}
CLASS_MAP = {
1: "Art",
2: "Geography",
3: "Science"
}
ENTRIES = {
"Monday": {
1: {
"class_name": CLASS_MAP[1],
"meeting_time": [9,10],
"meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1"
},
2: {
"class_name": CLASS_MAP[2],
"meeting_time": [10,12],
"meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1"
},
3: {
"class_name": CLASS_MAP[3],
"meeting_time": [12,13],
"meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1"
}
},
"Tuesday": {
1: {
"class_name": CLASS_MAP[2],
"meeting_time": [11,12],
"meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1"
},
},
"Wednesday": {
1: {
"class_name": CLASS_MAP[3],
"meeting_time": [12,13],
"meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1"
}
},
"Thursday": {
1: {
"class_name": CLASS_MAP[1],
"meeting_time": [14,15],
"meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1"
},
2: {
"class_name": CLASS_MAP[2],
"meeting_time": [17,18],
"meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1"
}
},
"Friday": {},
} |
# -*- coding: utf-8 -*-
def test_search_all(slack_time):
assert slack_time.search.all
def test_search_files(slack_time):
assert slack_time.search.files
def test_search_messages(slack_time):
assert slack_time.search.messages
|
class SegmentTreeNode:
def __init__(self, start, end, max):
self.start, self.end, self.max = start, end, max
self.left, self.right = None, None
class Solution:
"""
@param root: The root of segment tree.
@param index: index.
@param value: value
@return: nothing
"""
def modify(self, root, index, value):
if root.start == root.end and root.start == index :
root.max = value
return
mid = (root.start+root.end)//2
if index>mid :
self.modify(root.right,index,value)
else :
self.modify(root.left,index,value)
root.max = max(root.left.max,root.right.max)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2007, 2008 Torsten Bronger <bronger@physik.rwth-aachen.de>
#
# This file is part of the Bobcat program.
#
# Bobcat is free software; you can use it, redistribute it and/or modify it
# under the terms of the MIT license.
#
# You should have received a copy of the MIT license with Bobcat. If not,
# see <http://bobcat.origo.ethz.ch/wiki/Licence>.
#
"""The emitter is an object which organises output generation. This module
exports all of its functionality by the class `Emitter`."""
class Emitter(object):
"""Class for output generators.
The emitter is an object which holds all the output data and organises the
generation of the final output. In the simplest case, this is a file.
Howver, sometimes some post-processing is necessary. For example, the
generated LaTeX file must be transformed to a PDF.
Additionally, some output types may generate a whole bunch of files
(e.g. HTML, and even more so if you want to have each chapter in its own
file). Then, generating the output is more than just concatenating
`self.output`.
The emitter is instantiated in the backend module. The parser module
copies this into the `parser.Document` object and passes the settings
to it through `set_settings`. Then, the actual processing is done on the
AST, during which the `__call__` method is invoked very often with the
generated output text (in the correct order). Finally, the
`bobcatlib.parser.sectioning.Document` object in parser.py calls
`do_final_processing`. This method must be overridden in the derived class
in the backend! It can write self.output to a file for example or more.
:ivar output: serialised output of the current document processing.
:ivar settings: settings for the emitter like name of the input file and
further generation details (e.g. whether HTML sing file/multiple file).
:type output: unicode
:type settings: dict
"""
def __init__(self):
"""Class constructor."""
self.output = u""
self.settings = None
def set_settings(self, settings):
"""Setting the settings for the output. It is possible to set the
settings by a mere assignment to `Emitter.settings` but this is
clearer. This method is called before any `__call__` or
`do_final_processing` call so that you can use the settings in these
methods.
:Parameters:
- `settings`: the output setting, e.g. the original input filename
from which the output filename can be derived.
:type settings: dict
"""
self.settings = settings
def __repr__(self):
return "Emitter()"
def __call__(self, text):
"""Emit a certain excerpt of text. You may use `self.settings` in this
method.
:Parameters:
- `text`: the excerpt of text that is supposed to be appended to the
current output.
:type text: preprocessor.Excerpt
"""
self.output += unicode(text)
def pop_output(self):
"""Returns the output emitted so far and resets the output to the empty
string.
:Return:
the output emitted so far
:rtype: unicode
"""
output = self.output
self.output = u""
return output
def do_final_processing(self):
"""This method generates the actual output, i.e. writes to files,
creates subdirectories, calls post-processing conversion programs,
prepares all images etc. It is called from the
`parser.sectioning.Document.generate_output` method in the
`sectioning.Document` root node.
The method is not defined in this abstract base class, so it must be
overridden in the derived class in the backend. You may use
`self.settings` in this method."""
raise NotImplementedError
|
#!/usr/bin/env python3
#Altere o programa de cálculo dos números primos, informando, caso o número não seja primo, por quais número ele é divisível.
contador=0
divisores=[]
numero=int(input("Digite o número: "))
if numero!=-1 and numero!=0 and numero!=1:
for divisor in range(1,numero+1):
if numero%divisor==0:
contador+=1 #O contador aumenta quando há um divisor
divisores.append(divisor)
if contador>2:
print(numero,"não é um número primo")
print("Divisores",divisores)
else:
print(numero,"é um número primo")
else:
print(numero,"não é um número primo")
|
class RssItem:
"""A class used to represent an RSS post"""
def __init__(self, title, description, link, pub_date):
self.title = title
self.description = description
self.link = link
self.pub_date = pub_date |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Pre-caching steps used internally by the IDL compiler
#
# Design doc: http://www.chromium.org/developers/design-documents/idl-build
{
'includes': [
'scripts.gypi',
'../bindings.gypi',
'../templates/templates.gypi',
],
'targets': [
################################################################################
{
# This separate pre-caching step is required to use lex/parse table caching
# in PLY, since PLY itself does not check if the cache is valid, and may end
# up using a stale cache if this step hasn't been run to update it.
#
# This action's dependencies *is* the cache validation.
#
# GN version: //third_party/WebKit/Source/bindings/scripts:cached_lex_yacc_tables
'target_name': 'cached_lex_yacc_tables',
'type': 'none',
'actions': [{
'action_name': 'cache_lex_yacc_tables',
'inputs': [
'<@(idl_lexer_parser_files)',
],
'outputs': [
'<(bindings_scripts_output_dir)/lextab.py',
'<(bindings_scripts_output_dir)/parsetab.pickle',
],
'action': [
'python',
'blink_idl_parser.py',
'<(bindings_scripts_output_dir)',
],
'message': 'Caching PLY lex & yacc lex/parse tables',
}],
},
################################################################################
{
# A separate pre-caching step is *required* to use bytecode caching in
# Jinja (which improves speed significantly), as the bytecode cache is
# not concurrency-safe on write; details in code_generator_v8.py.
#
# GN version: //third_party/WebKit/Source/bindings/scripts:cached_jinja_templates
'target_name': 'cached_jinja_templates',
'type': 'none',
'actions': [{
'action_name': 'cache_jinja_templates',
'inputs': [
'<@(jinja_module_files)',
'code_generator_v8.py',
'<@(code_generator_template_files)',
],
'outputs': [
'<(bindings_scripts_output_dir)/cached_jinja_templates.stamp', # Dummy to track dependency
],
'action': [
'python',
'code_generator_v8.py',
'<(bindings_scripts_output_dir)',
'<(bindings_scripts_output_dir)/cached_jinja_templates.stamp',
],
'message': 'Caching bytecode of Jinja templates',
}],
},
################################################################################
], # targets
}
|
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: enums
class DateGenerationRule(object):
Backward = 0
CDS = 1
Forward = 2
OldCDS = 3
ThirdWednesday = 4
Twentieth = 5
TwentiethIMM = 6
Zero = 7
|
n=int(input("Enter a number:"))
print("The number is",n)
sum=0
while(n>0 or sum>9):
if(n==0):
n=sum
sum=0
sum=sum+n%10
n=n//10
print(f"sum of the digits is:", sum)
if(sum==1):
print("it is a magic number")
else:
print("It is not a magic number")
|
# https://docs.python.org/3/library/exceptions.html
class person:
def __init__(self, age, name):
if type(age)!=int:
raise Exception("Invaild Age: {}".format(age))
if age<0:
raise Exception("Invaild Age: {}".format(age))
if type(name)!=str:
raise Exception("Name not string: {}".format(name))
self.name=name
self.age=age
x=person("-9", 1243)
|
#Exercise!
#Display the image below to the right hand side where the 0 is going to be ' ',
# and the 1 is going to be '*'. This will reveal an image!
picture = [
[0,0,0,1,0,0,0],
[0,0,1,1,1,0,0],
[0,1,1,1,1,1,0],
[1,1,1,1,1,1,1],
[0,0,0,1,0,0,0],
[0,0,0,1,0,0,0]
]
#version 1
# for y_list in picture:
# row_image = ""
# for x in y_list:
# if x:
# row_image += "*"
# else:
# row_image += " "
# print(row_image)
#version 2
fill = "*"
space = " "
empty = ""
for row in picture:
for pixel in row:
if pixel:
#overwrite the end to "" instead of new line for print function
print(fill, end=empty)
else:
print(space, end=empty)
#new line after each row
print(empty) |
f = open('rucsac.txt', 'r')
n = int(f.readline())
v = []
for i in range(n):
linie = f.readline().split()
v.append((i+1, int(linie[0]), int(linie[1])))
G = int(f.readline())
cmax = [[0 for i in range(G+1)] for j in range(n+1)]
for i in range(1, n+1):
for j in range(1, G+1):
if v[i-1][1] > j:
cmax[i][j] = cmax[i-1][j]
else:
cmax[i][j] = max(cmax[i-1][j], v[i-1][2] + cmax[i-1][j-v[i-1][1]])
print("Profitul maxim care poate fi obtinut este %s, introducand obiectele: " % cmax[n][G], end = '')
i, j = n, G
solutie = []
while i > 0:
if cmax[i][G] != cmax[i-1][G]:
solutie.append(v[i][0])
j -= v[i][1]
i -= 1
else:
i -= 1
for elem in reversed(solutie):
print(elem, end = ' ')
f.close() |
for _ in range(int(input())):
a,b = map(str,input().split())
l1 = len(a)
l2 = len(b)
flag = True
k = ""
while l1>0 and l2>0:
if a[-1]<=b[-1]:
l1-=1
l2-=1
a1 = a[-1]
b1 = b[-1]
a = a[:-1]
b = b[:-1]
a1 = int(a1)
b1 = int(b1)
if not (b1-a1 <10):
flag = False
break
else:
k = f"{b1-a1}" + k
else:
l1-=1
l2-=2
if l2>=0:
pass
if l2<0:
flag = False
break
a1 = a[-1]
b1 = b[-2:]
a = a[:-1]
b = b[:-2]
a1 = int(a1)
b1 = int(b1)
if not (b1-a1 <10 and b1-a1>=0):
flag = False
break
else:
k = f"{b1-a1}" + k
if not (l1 or not flag):
print(int(b+k))
else:
print(-1)
|
BILL_TYPES = {
'hconres': 'House Concurrent Resolution',
'hjres': 'House Joint Resolution',
'hr': 'House Bill',
'hres': 'House Resolution',
'sconres': 'Senate Concurrent Resolution',
'sjres': 'Senate Joint Resolution',
's': 'Senate Bill',
'sres': 'Senate Resolution',
}
|
def is_file_h5(item):
output = False
if type(item)==str:
if item.endswith('.h5') or item.endswith('.hdf5'):
output = True
return output
|
class World:
def __init__(self):
self.children = []
def addChild(self, child):
child.world = self
self.children.append(child)
def getChildByName(self, name):
for child in self.children:
if child.name == name:
return name
return None
def getAllChildren(self):
return self.children
|
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g = sorted(g)
s = sorted(s)
ans = 0
start = 0
for x in range(0, len(s)):
for y in range(start, len(g)):
if s[x] >= g[y]:
ans += 1
start = y + 1
break
return ans
|
""" Enumerates results and states used by Go CD. """
ASSIGNED = 'Assigned'
BUILDING = 'Building'
CANCELLED = 'Cancelled'
COMPLETED = 'Completed'
COMPLETING = 'Completing'
DISCONTINUED = 'Discontinued'
FAILED = 'Failed'
FAILING = 'Failing'
PASSED = 'Passed'
PAUSED = 'Paused'
PREPARING = 'Preparing'
RESCHEDULED = 'Rescheduled'
SCHEDULED = 'Scheduled'
UNKNOWN = 'Unknown'
WAITING = 'Waiting'
JOB_RESULTS = [
CANCELLED,
FAILED,
PASSED,
UNKNOWN,
]
JOB_STATES = [
ASSIGNED,
BUILDING,
COMPLETED,
COMPLETING,
DISCONTINUED,
PAUSED,
PREPARING,
RESCHEDULED,
SCHEDULED,
UNKNOWN,
WAITING,
]
STAGE_RESULTS = [
CANCELLED,
FAILED,
PASSED,
UNKNOWN,
]
STAGE_STATES = [
BUILDING,
CANCELLED,
FAILED,
FAILING,
PASSED,
UNKNOWN,
]
|
# Taken from https://engineering.semantics3.com/a-simplified-guide-to-grpc-in-python-6c4e25f0c506
def message_to_send(x):
if x=="hi":
return 'hello, how can i help you'
elif x=="good afternoon":
return "good afternoon, how you doing"
elif x== 'Do you think you can really help me?':
return 'Yes, Of Course I can!'
elif x == 'How can I contact You?':
return 'You can call me on 8906803353, 24*7!'
elif x == 'What is the purpose of this chat?':
return 'Not everything has a Purpose, LOL!'
elif x == 'How do I know you?':
return 'It is very simple... I am the server, You are My client!'
elif x == 'Was this a joke?':
return 'I do not know.. Do I seem like a Joker to you??'
elif x == ' I am so tired of talking to you!':
return ' That is because you are RUNNING in your thoughts while talking to me!!'
elif x == ' That is it. I no longer want to talk to you! This chat is over...':
return 'Well, In that case you can talk to my creators Shankar and Ankit.'
elif x == 'Not that drama again.. I know you are good at it! Okay, I forgive you..':
return 'I knew it.. Love you too!'
else:
return "type something please"
'''
elif x == 'Do you think you can really help me?':
return 'Yes, Of Course I can!'
elif x == 'How can I contact You?':
return 'You can call me on 8906803353, 24*7!'
elif x == 'What is the purpose of this chat?':
return 'Not everything has a Purpose, LOL!'
elif x == 'How do I know you?':
return 'It is very simple... I am the server, You are My client!'
elif x == 'Was this a joke?':
return 'I do not know.. Do I seem like a Joker to you??'
elif x == ' I am so tired of talking to you!':
return ' That is because you are RUNNING in your thoughts while talking to me!!'
elif x == ' That is it. I no longer want to talk to you! This chat is over...':
return 'Well, you all are the same. Leave me alone all the time. It seems my heart will break again!'
elif x == 'Not that drama again.. I know you are good at it! Okay, I forgive you..':
return 'I knew it.. Love you too!'
elif x=="exit" or "bye":
pass
else:
return 'Do not be mad at me please. Say something!'
'''
|
'''
URL: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/
Time complexity: O(n)
Space complexity: O(1)
'''
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
start = 0
for i in range(1, len(nums)):
if nums[i] < nums[start]:
while start >= 0 and nums[i] < nums[start]:
start -= 1
start += 1
break
start += 1
if start == len(nums) - 1:
return 0
end = len(nums) - 1
for i in range(len(nums)-2, -1, -1):
if nums[i] > nums[end]:
while end < len(nums) and nums[i] > nums[end]:
end += 1
end -= 1
break
end -= 1
min_val, max_val = nums[start], nums[end]
for i in range(start, end+1):
min_val = min(min_val, nums[i])
max_val = max(max_val, nums[i])
u_start, u_end = -1, -1
for i in range(start):
if min_val < nums[i]:
u_start = i
break
for j in range(len(nums)-1, end, -1):
if max_val > nums[j]:
u_end = j
break
if u_start == -1:
u_start = start
if u_end == -1:
u_end = end
return u_end - u_start + 1
|
dia = int(input("\033[1;31mDia\033[m = "))
mes = str(input("\033[1;32mMês\033[m = "))
ano = int(input("\033[1;36mAno\033[m = "))
print("Você nasceu no dia\033[1;36m", dia, "\033[mde \033[1;32m" + mes + "\033[m de\033[1;31m", ano, "\033[m. \033[4;37mCerto!?\033[m")
|
# Python program to implement graph deletion operation | delete node | using dictionary
nodes = []
graph = {}
# delete a node undirected and unweighted
def delete_node(val):
if val not in graph:
print(val, "is not present in the graph")
else:
graph.pop(val) # pop the key with all values
for i in graph: # traverse the dictionary
list1 = graph[i] # assign values to list
if val in list1:
return list1.remove(val) # remove the value
# delete a node directed and wighted graph
def delete_node(val):
if val not in graph:
print(val, "is not present in the graph")
else:
graph.pop(val) # pop the key with all values
for i in graph: # traverse the dictionary
list1 = graph[i] # assign values to list
for j in list1: # search for the value in list1 nested list
if val == j[0]: # check first index of the value
list1.remove(j)
break
delete_node("A")
delete_node("B") |
with open('day14/input.txt') as f:
lines = f.readlines()
dic = {}
for line in lines:
a, b = line.strip().split(" -> ")
dic[a] = b
def grow(poly: str) -> str:
result = ""
for i in range(len(poly) - 1):
q = poly[i:i+2]
result += poly[i] +dic[q]
result += poly[-1]
return result
# poly = "NNCB" # sample
poly = "CKFFSCFSCBCKBPBCSPKP"
for i in range(40):
print(i+1)
# print(f"{i+1}: {poly}")
poly = grow(poly)
counts = {}
for p in poly:
if p in counts:
counts[p] += 1
else:
counts[p] = 1
counts = sorted(counts.values())
print(counts[-1] - counts[0])
|
n, m = map(int, input().split())
notes = [list(map(int, input().split())) for _ in range(m)]
if m == 1:
d, h = notes[0]
print(max(h+(d-1), h+(n-d)))
exit(0)
d0, h0 = notes[0]
ans = h0+(d0-1)
for i in range(m-1):
d1, h1 = notes[i]
d2, h2 = notes[i+1]
if d2-d1 < abs(h1-h2):
ans = -1
break
else:
ans = max((h1+h2+(d2-d1))//2, ans)
else:
dm, hm = notes[m-1]
ans = max(ans, hm+(n-dm))
print(ans if ans != -1 else 'IMPOSSIBLE')
|
t = int(input())
outs = []
for _ in range(t):
n = input()
a = list(map(int, input().split()))
if a[0] != a[1]:
correct = a[2]
else:
correct = a[0]
for i in range(len(a)):
if a[i] != correct:
outs.append(i+1)
break
for out in outs:
print(out) |
#Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa 60 reais por dia, e 0,15 centavos por Km rodado.
name = input('Olá, e bem vindo ao último challenge da aula, e mais uma vez, me fala o seu nome: ')
kmPercorridos = float(input('Shoow, {}! É ótimo você estar aqui até agora! Por favor, me fala quantos km o seu carro percorreu: '.format(name)))
daysRented = int(input('{}, agora me fala por quantos dias você ficou com esse carro: '.format(name)))
priceCalc = (60 * daysRented) + (kmPercorridos * 0.15)
print('{}, você me falou que ficou com o carro durante {} dias, e percorreu durante esse tempo um total de {} kilometros, logo o total a pagar é de R$ {} reais!'.format(name, daysRented, kmPercorridos, priceCalc )) |
d={
"Aligarh":"It is the city in UP ",
"bharatpur":"it is the city in Rajasthan",
"delhi ":"it is the capital of India",
"Mumbai":"it is the city in Maharashtra"
}
print("enter the name which you want to search ")
n1=input()
print(d[n1])
|
class Persona:
def __init__(self,nombre,apellidoPaterno,apellidoMaterno,sexo,edad,domicilio,telefono):
self.nombre = nombre
self.apellidoPaterno = apellidoPaterno
self.apellidoMaterno = apellidoMaterno
self.sexo = sexo
self.edad = edad
self.domicilio = domicilio
self.telefono = telefono
def getNombre(self):
return self.nombre
def getApellidoPaterno(self):
return self.apellidoPaterno
def getApellidoMaterno(self):
return self.apellidoMaterno
def getSexo(self):
return self.sexo
def getEdad(self):
return self.edad
def getDomicilio(self):
return self.domicilio
def getTelefono(self):
return self.telefono
def setNombre(self,nombre):
self.nombre = nombre
def setApellidoPaterno(self,apellidoPaterno):
self.apellidoPaterno = apellidoPaterno
def setApellidoMaterno(self,apellidoMaterno):
self.apellidoMaterno = apellidoMaterno
def setSexo(self,sexo):
self.sexo = sexo
def setEdad(self,edad):
self.edad = edad
def setDomicilio(self,domicilio):
self.domicilio = domicilio
def setTelefono(self,telefono):
self.telefono = telefono
|
# 1. Write a Python class named Rectangle constructed by a length and width and a method which will
# compute the area of a rectangle.
class rectangle():
def __init__(self, width, length):
self.width = width
self.length = length
def area(self):
return self.width * self.length
a = int(input("Enter length of rectangle: "))
b = int(input("Enter width of rectangle: "))
obj = rectangle(a, b)
print("Area of rectangle:", obj.area())
print() |
CONNECTION_TAB_DEFAULT_TITLE = "Untitled"
CONNECTION_STRING_SUPPORTED_DB_NAMES = ["SQLite"]
CONNECTION_STRING_PLACEHOLDER = "Enter..."
CONNECTION_STRING_DEFAULT = "demo.db"
QUERY_EDITOR_DEFAULT_TEXT = "SELECT name FROM sqlite_master WHERE type='table'"
QUERY_CONTROL_CONNECT_BUTTON_TEXT = "Connect"
QUERY_CONTROL_EXECUTE_BUTTON_TEXT = "Execute"
QUERY_CONTROL_FETCH_BUTTON_TEXT = "Fetch"
QUERY_CONTROL_COMMIT_BUTTON_TEXT = "Commit"
QUERY_CONTROL_ROLLBACK_BUTTON_TEXT = "Rollback"
QUERY_RESULTS_DATA_TAB_TEXT = "Data"
QUERY_RESULTS_EVENTS_TAB_TEXT = "Events"
|
# -*- coding: utf-8 -*-
# Copyright 2015 Pietro Brunetti <pietro.brunetti@itb.cnr.it>
#
# 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.
__authors__ = "Pietro Brunetti"
__all__ = ["peptidome",
"raw",
"by_targets",
"ChangeTargetPeptides",
'DialogCommons',
'EPPI_data'
"EPPI",
'flatnotebook',
'html_generator',
'Join',
'ManageVars',
'pages',
'project',
'ReportProtein,'
'ReportSequence',
'Resume',
'Search',
'SelPepts',
'Targets']
|
#!/usr/bin/python
# This script simply generates a table of the voltage to expect
# if I combine my photoresistors with some of my resitors from stock..
# As there is no strong sunlight at the moment here, I will have to
# postpone the real life testing..
voltage=5.
resistor=[59,180,220,453,750,1000,10000,20000]
measurement=[2000000, 1000000, 600000, 200000, 100000, 80000, 40000, 20000, 10000, 8000, 6000, 4000, 2000, 1000, 800, 600, 400, 200, 100, 80, 60, 40, 20, 8, 2]
def measure(r,p):
return round(voltage-(voltage/(r+p)*r),4)
print("")
print("Photoresistor Simulation")
print("------------------------")
print("")
print("Setup:")
print(" -----[R]---+--(~)---- 5V")
print(" | |")
print(" = 0V {?}")
print(" |")
print(" = 0V")
print("")
print("Table of expected voltage for a given resistor and the resistance")
print("at a certain light exposure (in Ohm):")
print("")
s="~ \\ R\t\t"
for r in resistor:
s+=str(r)+"\t"
print(s)
print("")
for m in measurement:
s=str(m) + "\t\t"
for r in resistor:
s+=str(measure(m,r)) + "\t"
print(s)
|
# Calculates total acres based on square feet input
# Declare variables
sqftInOneAcre = 43560
# Prompt user for total square feet of parcel of land
totalSqft = float(input('\nEnter total square feet of parcel of land: '))
# Calculate and display total acres
totalAcres = totalSqft / sqftInOneAcre
print('Total acres: ', format(totalAcres, ',.1f'), '\n')
|
class ReportEntry:
def __init__(self):
self.medium = 'Book'
self.title = None
self.url = None
self.classification = None
self.length = None
self.start_date = None
self.stop_date = None
self.distribution_percent = None
|
def rank_cal(rank_list, target_index):
rank = 0.
target_score = rank_list[target_index]
for score in rank_list:
if score >= target_score:
rank += 1.
return rank
def reciprocal_rank(rank):
return 1./rank
def accuracy_at_k(rank, k):
if rank <= k:
return 1.
else:
return 0.
def rank_eval_example(pred, labels):
mrr = []
macc1 = []
macc5 = []
macc10 = []
macc50 = []
cur_pos = []
for i in range(len(pred)):
rank = rank_cal(cas_pred[i], cas_labels[i])
mrr.append(reciprocal_rank(rank))
macc1.append(accuracy_at_k(rank,1))
macc5.append(accuracy_at_k(rank,5))
macc10.append(accuracy_at_k(rank,10))
macc50.append(accuracy_at_k(rank,50))
return mrr, macc1, macc5, macc10, macc50
def rank_eval(pred, labels, sl):
mrr = 0
macc1 = 0
macc5 = 0
macc10 = 0
macc50 = 0
macc100 = 0
cur_pos = 0
for i in range(len(sl)):
length = sl[i]
cas_pred = pred[cur_pos : cur_pos+length]
cas_labels = labels[cur_pos : cur_pos+length]
cur_pos += length
rr = 0
acc1 = 0
acc5 = 0
acc10 = 0
acc50 = 0
acc100 = 0
for j in range(len(cas_pred)):
rank = rank_cal(cas_pred[j], cas_labels[j])
rr += reciprocal_rank(rank)
acc1 += accuracy_at_k(rank,1)
acc5 += accuracy_at_k(rank,5)
acc10 += accuracy_at_k(rank,10)
acc50 += accuracy_at_k(rank,50)
acc100 += accuracy_at_k(rank,100)
mrr += rr/float(length)
macc1 += acc1/float(length)
macc5 += acc5/float(length)
macc10 += acc10/float(length)
macc50 += acc50/float(length)
macc100 += acc100/float(length)
return mrr, macc1, macc5, macc10, macc50, macc100 |
BELI = 'b'
ČRNI = 'č'
KMET = 'P'
TRDNJAVA = 'R'
KONJ = 'N'
TEKAČ = 'B'
KRALJICA = 'Q'
KRALJ = 'K'
ZMAGA = 'W'
PORAZ = 'X'
NAPAČNA_POTEZA = 'xx'
ZAČETEK = 'S'
# začetno stanje:
začetna_polja = { (1, 1): (BELI, TRDNJAVA), (1, 2): (BELI, KONJ), (1, 3): (BELI, TEKAČ), (1, 4): (BELI, KRALJICA), (1, 5): (BELI, KRALJ), (1, 6): (BELI, TEKAČ), (1, 7): (BELI, KONJ), (1, 8): (BELI, TRDNJAVA),
(2, 1): (BELI, KMET), (2, 2): (BELI, KMET), (2, 3): (BELI, KMET), (2, 4): (BELI, KMET), (2, 5): (BELI, KMET), (2, 6): (BELI, KMET), (2, 7): (BELI, KMET), (2, 8): (BELI, KMET),
(7, 1): (ČRNI, KMET), (7, 2): (ČRNI, KMET), (7, 3): (ČRNI, KMET), (7, 4): (ČRNI, KMET), (7, 5): (ČRNI, KMET), (7, 6): (ČRNI, KMET), (7, 7): (ČRNI, KMET), (7, 8): (ČRNI, KMET),
(8, 1): (ČRNI, TRDNJAVA), (8, 2): (ČRNI, KONJ), (8, 3): (ČRNI, TEKAČ), (8, 4): (ČRNI, KRALJICA), (8, 5): (ČRNI, KRALJ), (8, 6): (ČRNI, TEKAČ), (8, 7): (ČRNI, KONJ), (8, 8): (ČRNI, TRDNJAVA)}
# razredi figur (vsi imajo metodo poteze, ki vrne množico vseh možnih potez iz danega polja, kralj in kmet imata še metodo ogroža, ki vrne množico vseh polj, ki ju ogrožata):
class trdnjava:
def __init__(self, barva, polje, svoja_polja, nasprotnikova_polja):
self.v, self.s = polje
self.barva = barva
self.nasprotnikova_polja = nasprotnikova_polja
self.svoja_polja = svoja_polja
def poteze(self):
množica = set()
# dol
for i in range(1, self.v)[::-1]:
if (i, self.s) in self.nasprotnikova_polja:
množica.update({(i, self.s)})
break
if (i, self.s) in self.svoja_polja:
break
množica.update({(i, self.s)})
# gor
for i in range(self.v + 1, 9):
if (i, self.s) in self.nasprotnikova_polja:
množica.update({(i, self.s)})
break
if (i, self.s) in self.svoja_polja:
break
množica.update({(i, self.s)})
# levo
for i in range(1, self.s)[::-1]:
if (self.v, i) in self.nasprotnikova_polja:
množica.update({(self.v, i)})
break
if (self.v, i) in self.svoja_polja:
break
množica.update({(self.v, i)})
# desno
for i in range(self.s + 1, 9):
if (self.v, i) in self.nasprotnikova_polja:
množica.update({(self.v, i)})
break
if (self.v, i) in self.svoja_polja:
break
množica.update({(self.v, i)})
return množica
class tekač:
def __init__(self, barva, polje, svoja_polja, nasprotnikova_polja):
self.v, self.s = polje
self.nasprotnikova_polja = nasprotnikova_polja
self.svoja_polja = svoja_polja
def poteze(self):
množica = set()
# desno gor
for i in range(1, min(9 - self.v, 9 - self.s)):
if (self.v + i, self.s + i) in self.nasprotnikova_polja:
množica.update({(self.v + i, self.s + i)})
break
if (self.v + i, self.s + i) in self.svoja_polja:
break
množica.update({(self.v + i, self.s + i)})
# desno dol
for i in min(range(1, self.v), range(1, 9 - self.s), key=len):
if (self.v - i, self.s + i) in self.nasprotnikova_polja:
množica.update({(self.v - i, self.s + i)})
break
if (self.v - i, self.s + i) in self.svoja_polja:
break
množica.update({(self.v - i, self.s + i)})
# levo gor
for i in min(range(1, self.s), range(1, 9 - self.v), key=len):
if (self.v + i, self.s - i) in self.nasprotnikova_polja:
množica.update({(self.v + i, self.s - i)})
break
if (self.v + i, self.s - i) in self.svoja_polja:
break
množica.update({(self.v + i, self.s - i)})
# levo dol
for i in range(1, min(self.v, self.s)):
if (self.v - i, self.s - i) in self.nasprotnikova_polja:
množica.update({(self.v - i, self.s - i)})
break
if (self.v - i, self.s - i) in self.svoja_polja:
break
množica.update({(self.v - i, self.s - i)})
return množica
class konj:
def __init__(self, barva, polje, svoja_polja, nasprotnikova_polja):
self.v, self.s = polje
self.nasprotnikova_polja = nasprotnikova_polja
self.svoja_polja = svoja_polja
def poteze(self):
množica = set()
for i in [2, -2]:
for j in [1, -1]:
# pogoj je, da na polju ni črne figure in da ne skoči iz plošče
if not (self.v + i, self.s + j) in self.svoja_polja and 9 > self.v + i > 0 and 9 > self.s + j > 0:
množica.update({(self.v + i, self.s + j)})
if not (self.v + j, self.s + i) in self.svoja_polja and 9 > self.v + j > 0 and 9 > self.s + i > 0:
množica.update({(self.v + j, self.s + i)})
return množica
class kraljica:
def __init__(self, barva, polje, svoja_polja, nasprotnikova_polja):
self.v, self.s = polje
self.barva = barva
self.nasprotnikova_polja = nasprotnikova_polja
self.svoja_polja = svoja_polja
def poteze(self):
diagonala = tekač(self.barva, (self.v, self.s), self.svoja_polja, self.nasprotnikova_polja).poteze()
vodoravno_in_navpično = trdnjava(self.barva, (self.v, self.s), self.svoja_polja, self.nasprotnikova_polja).poteze()
return diagonala.union(vodoravno_in_navpično)
class kmet:
def __init__(self, barva, polje, svoja_polja, nasprotnikova_polja, zasedena_polja):
self.v, self.s = polje
self.barva = barva
self.nasprotnikova_polja = nasprotnikova_polja
self.svoja_polja = svoja_polja
self.zasedena_polja = zasedena_polja
if barva == BELI:
self.premik = 1
self.začetek = 2
else:
self.premik = - 1
self.začetek = 7
def ogroža(self):
return {(self.v + self.premik, self.s + 1), (self.v + self.premik, self.s - 1)}
def poteze(self):
množica = set()
if (self.v + self.premik, self.s - 1) in self.nasprotnikova_polja:
množica.update({(self.v + self.premik, self.s - 1)})
if (self.v + self.premik, self.s + 1) in self.nasprotnikova_polja:
množica.update({(self.v + self.premik, self.s + 1)})
if (self.v + self.premik, self.s) in self.zasedena_polja:
return množica
if self.v == self.začetek:
množica.update({(self.začetek + self.premik, self.s)})
if (self.začetek + 2 * self.premik, self.s) not in self.zasedena_polja:
množica.update({(self.začetek + 2 * self.premik, self.s)})
else:
množica.update({(self.v + self.premik, self.s)})
return množica
# zaradi kraljevih potez moram še pogledati ogrožena polja:
def poteze(figura, polje, barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
if figura == KMET:
return kmet(barva, polje, svoja_polja, nasprotnikova_polja, zasedena_polja).poteze()
if figura == TRDNJAVA:
return trdnjava(barva, polje, svoja_polja, nasprotnikova_polja).poteze()
if figura == TEKAČ:
return tekač(barva, polje, svoja_polja, nasprotnikova_polja).poteze()
if figura == KONJ:
return konj(barva, polje, svoja_polja, nasprotnikova_polja).poteze()
if figura == KRALJICA:
return kraljica(barva, polje, svoja_polja, nasprotnikova_polja).poteze()
else:
return kralj(barva, polje, svoja_polja, nasprotnikova_polja, zasedena_polja).poteze()
def ogrožena_polja_za(barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
množica = set()
for polje in nasprotnikova_polja:
barva, figura = zasedena_polja[polje]
if figura == KMET:
množica.update(kmet(barva, polje, nasprotnikova_polja, svoja_polja, zasedena_polja).ogroža())
elif figura == KRALJ:
množica.update(kralj(barva, polje, nasprotnikova_polja, svoja_polja, zasedena_polja).ogroža())
else:
množica.update(poteze(figura, polje, barva, nasprotnikova_polja, svoja_polja, zasedena_polja))
return množica
class kralj:
def __init__(self, barva, polje, svoja_polja, nasprotnikova_polja, zasedena_polja):
self.v, self.s = polje
self.barva = barva
self.svoja_polja = svoja_polja
self.nasprotnikova_polja = nasprotnikova_polja
self.postavitev = zasedena_polja
def ogroža(self):
množica = set()
for i in [-1, 1, 0]:
for j in [-1, 1, 0]:
if not j == 0 == i:
if not (self.v + i, self.s + j) in self.svoja_polja.union(množica) and 9 > self.v + i > 0 and 9 > self.s + j > 0:
množica.update({(self.v + i, self.s + j)})
if not (self.v - i, self.s - j) in self.svoja_polja.union(množica) and 9 > self.v - i > 0 and 9 > self.s - j > 0:
množica.update({(self.v - i, self.s - j)})
return množica
def poteze(self):
return (self.ogroža()).difference(ogrožena_polja_za(self.barva, self.svoja_polja, self.nasprotnikova_polja, self.postavitev))
# kriteriji, po katerih se avalvira, kako dobra je situacija za barvo
def ogroženost(barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
ogroženost = 0
ogrožena_polja = ogrožena_polja_za(barva, svoja_polja, nasprotnikova_polja, zasedena_polja)
for polje in svoja_polja:
if polje in ogrožena_polja:
ogroženost += 1
return ogroženost
vrednosti_figur = {KMET: 1,
KONJ: 3,
TEKAČ: 3,
TRDNJAVA: 5,
KRALJICA: 9}
def vrednost(barva, svoja_polja, zasedena_polja):
vrednost = 0
for polje in svoja_polja:
figura = zasedena_polja[polje][1]
if figura != KRALJ:
vrednost += vrednosti_figur[figura]
return vrednost
def na_katerih_poljih_je(figura, barva, zasedena_polja): # to funkcijo bom potreboval pri naslednjih treh kriterijih
for polje in zasedena_polja:
if zasedena_polja[polje] == (barva, figura):
return polje
return set()
def zaprtost_kralja(barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
polje = na_katerih_poljih_je(KRALJ, barva, zasedena_polja)
return len(kralj(barva, polje, svoja_polja, nasprotnikova_polja, zasedena_polja).poteze())
def ogroženost_kralja(barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
polje = na_katerih_poljih_je(KRALJ, barva, zasedena_polja)
if polje in ogrožena_polja_za(barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
return 2
else:
return 0
def ogroženost_kraljice(barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
polje = na_katerih_poljih_je(KRALJICA, barva, zasedena_polja)
if polje == set():
return 0
if polje in ogrožena_polja_za(barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
return 2
else:
return 0
def zasedenost_centra(barva, svoja_polja):
zasedenost = 0
for v in range(3, 7):
for s in range(3, 7):
if (v, s) in svoja_polja:
zasedenost += 1
return zasedenost
def zmaga(nasprotnikova_barva, zasedena_polja):
return (nasprotnikova_barva, KRALJ) not in zasedena_polja.values()
# rang kriterijev, da vem, kako utežiti kriterije pri evalvaciji:
# ogroženost: 0 - 16 boljše manjše
# vrednost: 0 - 36 boljše večje
# zaprtost_kralja: 0 - 8 boljše večje
# ogroženost_kralja: 0 - 2 boljše manjše
# ogroženost_kraljice: 0 - 2 boljše manjše
# zasedenost_centra: 0 - 16 boljše večje
def evalvacija(barva, svoja_polja, nasprotnikova_polja, zasedena_polja):
if barva == BELI:
nasprotna_barva = ČRNI
else:
nasprotna_barva = BELI
if zmaga(nasprotna_barva, zasedena_polja):
return 100
if zmaga(barva, zasedena_polja):
return -100
evalvacija = 0
evalvacija += - ogroženost(barva, svoja_polja, nasprotnikova_polja, zasedena_polja) + ogroženost(nasprotna_barva, nasprotnikova_polja, svoja_polja, zasedena_polja)
evalvacija += (vrednost(barva, svoja_polja, zasedena_polja) - vrednost(nasprotna_barva, nasprotnikova_polja, zasedena_polja)) * 2
evalvacija += (zaprtost_kralja(barva, svoja_polja, nasprotnikova_polja, zasedena_polja) - zaprtost_kralja(nasprotna_barva, nasprotnikova_polja, svoja_polja, zasedena_polja)) / 2
evalvacija += - (ogroženost_kralja(barva, svoja_polja, nasprotnikova_polja, zasedena_polja) - ogroženost_kralja(nasprotna_barva, nasprotnikova_polja, svoja_polja, zasedena_polja)) * 4
evalvacija += - (ogroženost_kraljice(barva, svoja_polja, nasprotnikova_polja, zasedena_polja) - ogroženost_kraljice(nasprotna_barva, nasprotnikova_polja, svoja_polja, zasedena_polja)) * 3
evalvacija += (zasedenost_centra(barva, svoja_polja) - zasedenost_centra(nasprotna_barva, nasprotnikova_polja)) / 4
return evalvacija
class igra:
def __init__(self, barva, težavnost, stanje=None):
self.barva = barva # ta barva pripada računalniku
self.nasprotnikova_barva = {BELI, ČRNI}.difference({barva}).pop() # ta barva pripada igralcu
if stanje == ZAČETEK:
zasedena_polja = začetna_polja.copy()
self.postavitev = zasedena_polja
self.svoja_polja = {polje for polje in self.postavitev if self.postavitev[polje][0] == barva}
self.nasprotnikova_polja = set(self.postavitev.keys()).difference(self.svoja_polja)
self.težavnost = težavnost
def najboljša_poteza(self):
najboljša_ocena = self.težavnost * (-100)
iskano_polje, iskana_poteza = 0, 0
for polje in self.svoja_polja:
figura = self.postavitev[polje][1]
for poteza in poteze(figura, polje, self.barva, self.svoja_polja, self.nasprotnikova_polja, self.postavitev):
nova_postavitev = self.postavitev.copy()
par = nova_postavitev.pop(polje)
nova_postavitev[poteza] = par
nova_svoja_polja = {polje for polje in nova_postavitev if nova_postavitev[polje][0] == self.barva}
nova_nasprotnikova_polja = set(nova_postavitev.keys()).difference(nova_svoja_polja) # ker je lahko kakšna nasprotnikova figura pojedena
if zmaga(self.nasprotnikova_barva, nova_postavitev):
return (polje, poteza)
ocena = evalvacija(self.barva, nova_svoja_polja, nova_nasprotnikova_polja, nova_postavitev)
if self.težavnost > 1:
končna_ocena1 = 1000 # to bo evalvacija najslabse mozne poteze igralca za računalnik, ko igralec igra iz nove postavitve (raven 2)
for polje1 in nova_nasprotnikova_polja:
figura = nova_postavitev[polje1][1]
for poteza1 in poteze(figura, polje1, self.nasprotnikova_barva, nova_nasprotnikova_polja, nova_svoja_polja, nova_postavitev):
nova_postavitev1 = nova_postavitev.copy()
par1 = nova_postavitev1.pop(polje1)
nova_postavitev1[poteza1] = par1
nova_svoja_polja1 = {polje for polje in nova_postavitev1 if nova_postavitev1[polje][0] == self.barva}
nova_nasprotnikova_polja1 = set(nova_postavitev1.keys()).difference(nova_svoja_polja1) # ker je lahko kakšna nasprotnikova figura pojedena
if self.težavnost == 2:
ocena1 = evalvacija(self.barva, nova_svoja_polja1, nova_nasprotnikova_polja1, nova_postavitev1)
končna_ocena1 = min(končna_ocena1, ocena1) # najslabši mozen odziv igralca
if self.težavnost == 3:
končna_ocena2 = -1000 # to bo evalvacija najboljše možne poteze računalnika, po tem ko se je igralec že odzval na potezo računalnika
for polje2 in nova_svoja_polja1:
figura = nova_postavitev1[polje2][1]
for poteza2 in poteze(figura, polje2, self.barva, nova_svoja_polja1, nova_nasprotnikova_polja1, nova_postavitev1):
nova_postavitev2 = nova_postavitev1.copy()
par2 = nova_postavitev2.pop(polje2)
nova_postavitev2[poteza2] = par2
nova_svoja_polja2 = {polje for polje in nova_postavitev2 if nova_postavitev2[polje][0] == self.barva}
nova_nasprotnikova_polja2 = set(nova_postavitev2.keys()).difference(nova_svoja_polja2) # ker je lahko kakšna nasprotnikova figura pojedena
if zmaga(self.nasprotnikova_barva, nova_postavitev2):
ocena2 = 20
else:
ocena2 = evalvacija(self.barva, nova_svoja_polja2, nova_nasprotnikova_polja2, nova_postavitev2)
končna_ocena2 = max(končna_ocena2, ocena2)
končna_ocena1 = min(končna_ocena2, končna_ocena1)
if najboljša_ocena < končna_ocena1:
iskano_polje, iskana_poteza = polje, poteza
najboljša_ocena = končna_ocena1
else:
if najboljša_ocena < ocena:
iskano_polje, iskana_poteza = polje, poteza
najboljša_ocena = ocena
return (iskano_polje, iskana_poteza)
def naslednja_poteza(self, prejšnje_polje, novo_polje):
if prejšnje_polje not in self.nasprotnikova_polja or novo_polje not in poteze(self.postavitev[prejšnje_polje][1], prejšnje_polje, self.nasprotnikova_barva, self.nasprotnikova_polja, self.svoja_polja, self.postavitev):
return NAPAČNA_POTEZA
else:
(a, b) = self.postavitev.pop(prejšnje_polje)
if b == KMET and (novo_polje[0] == 8 or novo_polje[0] == 1):
self.postavitev[novo_polje] = (a, KRALJICA) # kmet se spremeni v kraljico
else:
self.postavitev[novo_polje] = (a, b)
self.svoja_polja = {polje for polje in self.postavitev if self.postavitev[polje][0] == self.barva}
self.nasprotnikova_polja = set(self.postavitev.keys()).difference(self.svoja_polja)
if zmaga(self.nasprotnikova_barva, self.postavitev):
return PORAZ
if zmaga(self.barva, self.postavitev):
return ZMAGA
def poteza_računalnika(self):
(prejšnje_polje, novo_polje) = self.najboljša_poteza()
(c, d) = self.postavitev.pop(prejšnje_polje)
if d == KMET and novo_polje[0] == 8 or novo_polje[0] == 1:
self.postavitev[novo_polje] = (c, KRALJICA) # kmet se spremeni v kraljico
else:
self.postavitev[novo_polje] = (c, d)
self.svoja_polja = {polje for polje in self.postavitev if self.postavitev[polje][0] == self.barva}
self.nasprotnikova_polja = set(self.postavitev.keys()).difference(self.svoja_polja)
if zmaga(self.nasprotnikova_barva, self.postavitev):
return PORAZ
if zmaga(self.barva, self.postavitev):
return ZMAGA
def nova_igra(barva, težavnost):
nasprotnikova_barva = {BELI, ČRNI}.difference({barva}).pop()
return igra(nasprotnikova_barva, težavnost, ZAČETEK)
class sah:
def __init__(self):
self.igre = {}
def prost_id_igre(self):
if self.igre == {}:
return 0
else:
return max(self.igre.keys()) + 1
def nova_igra(self, barva, težavnost):
id_igre = self.prost_id_igre()
igra = nova_igra(barva, težavnost)
self.igre[id_igre] = (igra, ZAČETEK)
return id_igre
def poteza_igralca(self, id_igre, polje, poteza):
igra = self.igre[id_igre][0]
novo_stanje = igra.naslednja_poteza(polje, poteza)
self.igre[id_igre] = igra, novo_stanje
return novo_stanje
def poteza_računalnika(self, id_igre):
igra = self.igre[id_igre][0]
novo_stanje = igra.poteza_računalnika()
self.igre[id_igre] = igra, novo_stanje |
'''
Tratamento de erros.
Exceções. Não são necessáriamente erros no código.
NameError = Erro de nome, variável não iniciada.
ValueError = Erro de valor, não foi digitado algo do mesmo tipo solicitado.
ZeroDivisionError = Erro de divisão por zero.
TypeErroor = Erro de tipo.
IndexError = Erro de índice.
ModuleNotFoundError = Erro de modulo não encontrado.
Para tratamento de exceções vamos utilizar os comandos:
try: Operação.
except: Caso falhe.
else: Caso funcione.
finally: Caso falhe ou funcione.
Podemos utilizar o except Exception para mostra uma mesagem sobre o erro ocorrido.
Um mesmo 'try' pode ter vários 'exception'
'''
'''try:
a = int(input('Numerador: '))
b = int(input('Denomidaor: '))
r = a / b
except Exception as erro:
print(f'Problema encontrado foi {erro.__class__}')
else:
print(f'O resultado é {r:.1f}')
finally:
print('Volte sempre. Muito Obrigado.')'''
try:
a = int(input('Numerador: '))
b = int(input('Denomidaor: '))
r = a / b
except (ValueError, TypeError):
print('Tivemos um problema com os tipos de dados digitados.')
except ZeroDivisionError:
print('Não é possível dividir por zero.')
except KeyboardInterrupt:
print('O usuário preferiu não informar os dados.')
else:
print(f'O resultado é {r:.1f}')
finally:
print('Volte sempre. Muito Obrigado.') |
pos = 0
for k in range(6):
if float(input()) > 2: pos += 1
print(pos, "valores positivos")
|
# Exercício Python 043
# LEIA O PESO E ALTURA DE UMA PESSOA, CALCULE IMC E MOSTRAR STATUS:
# ABAIXO DE 18.5: ABAIXO DO PESO
# ENTRE 18.5 E 25: PESO IDEAL
# 25 ATE 30: SOBREPESO
# 30 ATE 40: OBESIDADE
# ACIMA DE 40: OBESIDADE MÓRBIDA
p = float(input('Digite o peso (kg): '))
h = float(input('Digite a altura (cm): '))
imc = p / ((h/100)**2)
if imc < 18.5:
print('O IMC é {:.2f} que corresponde a ABAIXO DO PESO'.format(imc))
elif imc >= 18.5 and imc < 25:
print('O IMC é {:.2f} que corresponde a PESO IDEAL'.format(imc))
elif imc >= 25 and imc < 30:
print('O IMC é {:.2f} que corresponde a SOBREPESO'.format(imc))
elif imc >= 30 and imc < 40:
print('O IMC é {:.2f} que corresponde a OBESIDADE'.format(imc))
else:
print('O IMC é {:.2f} que corresponde a OBESIDADE MÓRBIDA'.format(imc))
|
# Escreva um programa que pergunte a quantidade de dias pelos quais ele foi alugado e a quantidade de Km percorridos por um carro alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
dias = float(input('Quantos dias o carro foi alugado? '))
km = float(input('Quantos km foram percorridos? '))
pagar = (60 * dias) + (0.15 * km)
print('É necessário pagar R${:.2f}' .format(pagar)) |
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
if not any(matrix):
return
m, n = len(matrix), len(matrix[0])
self.tree = [[0] * (n + 1) for _ in range(m + 1)]
self.R = m + 1
self.C = n + 1
for i in range(m):
for j in range(n):
self.add(i + 1, j + 1, matrix[i][j])
self.matrix = matrix
def add(self, row, col, val):
i = row
while i < self.R:
j = col
while j < self.C:
self.tree[i][j] += val
j += (j & (-j))
i += (i & (-i))
def sumRange(self, row, col):
ans = 0
i = row
while i > 0:
j = col
while j > 0:
ans += self.tree[i][j]
j -= (j & (-j))
i -= (i & (-i))
return ans
def update(self, row: int, col: int, val: int) -> None:
self.add(row + 1, col + 1, val - self.matrix[row][col])
self.matrix[row][col] = val
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
return self.sumRange(row2 + 1, col2 + 1) - self.sumRange(row2 + 1, col1) - self.sumRange(row1, col2 + 1) + self.sumRange(row1, col1)
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# obj.update(row,col,val)
# param_2 = obj.sumRegion(row1,col1,row2,col2)
|
width = 800
height = 700
fps = 60
font_n = 'arial'
sheetload = "spritesheet_jumper.png"
mob_fq = 5000
player_acc = 0.5
player_friction = -0.12
player_gra = 0.8
player_jump = 21
platform_list = [(0,height-50),(width/2-50,height*3/4),
(235,height-350),(350,200),(175,100)]
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
sky = (0,142,205)
|
#Done by Carlos Amaral in 20/06/2020
"""
At this point, you’re a more capable programmer than you
were when you started this book. Now that you have a better sense of how
real-world situations are modeled in programs, you might be thinking of some
problems you could solve with your own programs. Record any new ideas you
have about problems you might want to solve as your programming skills con-
tinue to improve. Consider games you might want to write, data sets you might
want to explore, and web applications you’d like to create.
"""
#My own programs
boats = ['Iseo', 'Rivamare','Aquariva Super', 'DolceRiva New', 'Rivale', 'Perseo',
'Argo New']
available_boats = ['Iseo', 'Rivamare', 'Rivale']
for available_boat in available_boats:
if available_boat in boats:
print(f"Yes, {available_boat}, is available!")
else:
print(f"Sorry, {boat} is not available!")
|
n = int(input())
ans = 0
number = 0
for i in range(n):
a, b = map(int, input().split())
A = int(str(a)[::-1]) # reverse
B = int(str(b)[::-1]) # reverse
ans = A + B
number = int(str(ans)[::-1]) # reverse
print(number)
|
#***Library implementing the sorting algorithms***
def quick_sort(seq,less_than):
if len(seq) < 1:
return seq
else:
pivot=seq[0]
left = quick_sort([x for x in seq[1:] if less_than(x,pivot)],less_than)
right = quick_sort([x for x in seq[1:] if not less_than(x,pivot)],less_than)
return left + [pivot] + right
|
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Netflix, Inc.
Copyright (C) 2021 Stefano Gottardo (python porting)
SSDP Server helper
SPDX-License-Identifier: BSD-2-Clause
See LICENSES/BSD-2-Clause-Netflix.md for more information.
"""
# IMPORTANT: Make sure to maintain the header structure with exact spaces between header name and value,
# or some mobile apps may not recognise the values correctly.
# CACHE-CONTROL: max-age Amount of time in seconds that the NOTIFY packet should be cached by clients receiving it
# DATE: the format type is "Sat, 09 Jan 2021 09:27:22 GMT"
# M-SEARCH response let know where is the device descriptor XML
SEARCH_RESPONSE = '''\
HTTP/1.1 200 OK
LOCATION: http://{ip_addr}:{port}/ssdp/device-desc.xml
CACHE-CONTROL: max-age=1800
DATE: {date_timestamp}
EXT:
BOOTID.UPNP.ORG: {boot_id}
SERVER: Linux/2.6 UPnP/1.1 appcast_ssdp/1.0
ST: urn:dial-multiscreen-org:service:dial:1
USN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1
'''
# Notify that the service is changed
ADV_UPDATE = '''\
NOTIFY * HTTP/1.1
HOST: {udp_ip_addr}:{udp_port}
CACHE-CONTROL: max-age=1800
NT: urn:dial-multiscreen-org:service:dial:1
NTS: ssdp:alive
LOCATION: http://{ip_addr}:{port}/dd.xml
USN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1
'''
# Notify that the service is not available
ADV_BYEBYE = '''\
NOTIFY * HTTP/1.1
HOST: {udp_ip_addr}:{udp_port}
NT: urn:dial-multiscreen-org:service:dial:1
NTS: ssdp:byebye
USN: uuid:{device_uuid}::urn:dial-multiscreen-org:service:dial:1
'''
# Device descriptor XML
DD_XML = '''\
HTTP/1.1 200 OK
Content-Type: text/xml
Application-URL: http://{ip_addr}:{dial_port}/apps/
<?xml version="1.0"?>
<root xmlns="urn:schemas-upnp-org:device-1-0" xmlns:r="urn:restful-tv-org:schemas:upnp-dd">
<specVersion>
<major>1</major>
<minor>0</minor>
</specVersion>
<device>
<deviceType>urn:schemas-upnp-org:device:tvdevice:1</deviceType>
<friendlyName>{friendly_name}</friendlyName>
<manufacturer>{manufacturer_name}</manufacturer>
<modelName>{model_name}</modelName>
<UDN>uuid:{device_uuid}</UDN>
</device>
</root>
'''
|
class LigneTexte:
"""Une ligne de texte dans un document. """
def __init__(self, texte):
self.texte = texte
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.