content
stringlengths 7
1.05M
|
|---|
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
if len(numbers) <= 1:
return [None, None]
idx2 = len(numbers)-1
idx1 = 0
while idx1 < idx2:
if numbers[idx1] + numbers[idx2] == target:
return [idx1+1, idx2+1]
elif numbers[idx1] + numbers[idx2] <= target:
idx1 += 1
else:
idx2 -= 1
|
class SumUpException(Exception):
pass
class SumUpNoAccessCode(SumUpException):
pass
class SumUpAccessCodeExpired(SumUpException):
pass
|
# flake8: noqa
test_train_config = {"training_parameters": {"EPOCHS": 50}}
test_model_config = {"model_parameters": {"model_save_path": "modeloutput1"}}
test_test_data = {
"text": "what Homeowners Warranty Program means,what it applies to, what is its purpose?"
}
test_entities = [
{"text": "homeowners warranty program", "entity": "Fin_Corp", "start": 5, "end": 32}
]
test_training_data = [
{
"context": "what does Settlement means?",
"entities": [
{
"entity_value": "Settlement",
"entity_type": "Fin_Corp",
"start_index": 10,
"end_index": 20,
}
],
},
{
"context": "what does Home-Equity Loan means?",
"entities": [
{
"entity_value": "Home-Equity Loan",
"entity_type": "Fin_Corp",
"start_index": 10,
"end_index": 26,
}
],
},
{
"context": "what does Closed-Ended Credit stands for?",
"entities": [
{
"entity_value": "Closed-Ended Credit",
"entity_type": "Fin_Corp",
"start_index": 10,
"end_index": 29,
}
],
},
{
"context": "what does Adjustable-Rate Mortgage stands for?",
"entities": [
{
"entity_value": "Adjustable-Rate Mortgage",
"entity_type": "Fin_Corp",
"start_index": 10,
"end_index": 34,
}
],
},
{
"context": "what is the full form of Interest Cap ?",
"entities": [
{
"entity_value": "Interest Cap",
"entity_type": "Fin_Corp",
"start_index": 25,
"end_index": 37,
}
],
},
{
"context": "what is the full form of Title Insurance Policy ?",
"entities": [
{
"entity_value": "Title Insurance Policy",
"entity_type": "Fin_Corp",
"start_index": 25,
"end_index": 47,
}
],
},
{
"context": "what actually Mortgage Banker is ?",
"entities": [
{
"entity_value": "Mortgage Banker",
"entity_type": "Fin_Corp",
"start_index": 14,
"end_index": 29,
}
],
},
{
"context": "what actually Appraisal is ?",
"entities": [
{
"entity_value": "Appraisal",
"entity_type": "Fin_Corp",
"start_index": 14,
"end_index": 23,
}
],
},
{
"context": "what do Prepaid Items mean, explain the details",
"entities": [
{
"entity_value": "Prepaid Items",
"entity_type": "Fin_Corp",
"start_index": 8,
"end_index": 21,
}
],
},
{
"context": "what do Principal mean, explain the details",
"entities": [
{
"entity_value": "Principal",
"entity_type": "Fin_Corp",
"start_index": 8,
"end_index": 17,
}
],
},
{
"context": "I'm sorry, I'm not familiar with the meaning of Buyers Agent . What does that mean?",
"entities": [
{
"entity_value": "Buyers Agent",
"entity_type": "Fin_Corp",
"start_index": 48,
"end_index": 60,
}
],
},
{
"context": "I'm sorry, I'm not familiar with the meaning of Payment Cap . What does that mean?",
"entities": [
{
"entity_value": "Payment Cap",
"entity_type": "Fin_Corp",
"start_index": 48,
"end_index": 59,
}
],
},
{
"context": "Hello, Can you expand Sellers Agent ?",
"entities": [
{
"entity_value": "Sellers Agent",
"entity_type": "Fin_Corp",
"start_index": 22,
"end_index": 35,
}
],
},
{
"context": "Hello, Can you expand Floor ?",
"entities": [
{
"entity_value": "Floor",
"entity_type": "Fin_Corp",
"start_index": 22,
"end_index": 27,
}
],
},
{
"context": "What is Default ?",
"entities": [
{
"entity_value": "Default",
"entity_type": "Fin_Corp",
"start_index": 8,
"end_index": 15,
}
],
},
{
"context": "What is Amortization ?",
"entities": [
{
"entity_value": "Amortization",
"entity_type": "Fin_Corp",
"start_index": 8,
"end_index": 20,
}
],
},
{
"context": "What does Annual Percentage Rate mean?",
"entities": [
{
"entity_value": "Annual Percentage Rate",
"entity_type": "Fin_Corp",
"start_index": 10,
"end_index": 32,
}
],
},
{
"context": "What does Site-Built Housing mean?",
"entities": [
{
"entity_value": "Site-Built Housing",
"entity_type": "Fin_Corp",
"start_index": 10,
"end_index": 28,
}
],
},
{
"context": "Can you define what Amortization stands for and what it means?",
"entities": [
{
"entity_value": "Amortization",
"entity_type": "Fin_Corp",
"start_index": 20,
"end_index": 32,
}
],
},
{
"context": "Can you define what Fixed Interest Rate stands for and what it means?",
"entities": [
{
"entity_value": "Fixed Interest Rate",
"entity_type": "Fin_Corp",
"start_index": 20,
"end_index": 39,
}
],
},
{
"context": "I was looking over loan application could you explain what is meant by Point ?",
"entities": [
{
"entity_value": "Point",
"entity_type": "Fin_Corp",
"start_index": 71,
"end_index": 76,
}
],
},
{
"context": "I was looking over loan application could you explain what is meant by Net Income ?",
"entities": [
{
"entity_value": "Net Income",
"entity_type": "Fin_Corp",
"start_index": 71,
"end_index": 81,
}
],
},
{
"context": "I dont know what Interest stands for could you explain it clearly to me please?",
"entities": [
{
"entity_value": "Interest",
"entity_type": "Fin_Corp",
"start_index": 17,
"end_index": 25,
}
],
},
{
"context": "I dont know what Multiple Listing Service stands for could you explain it clearly to me please?",
"entities": [
{
"entity_value": "Multiple Listing Service",
"entity_type": "Fin_Corp",
"start_index": 17,
"end_index": 41,
}
],
},
{
"context": "what Homeowners Warranty Program means",
"entities": [
{
"entity_value": "Homeowners Warranty Program",
"entity_type": "Fin_Corp",
"start_index": 5,
"end_index": 32,
}
],
},
{
"context": "what Condominium means",
"entities": [
{
"entity_value": "Condominium",
"entity_type": "Fin_Corp",
"start_index": 5,
"end_index": 16,
}
],
},
{
"context": "Why is knowing your Interest Cap important?",
"entities": [
{
"entity_value": "Interest Cap",
"entity_type": "Fin_Corp",
"start_index": 20,
"end_index": 32,
}
],
},
{
"context": "Why is knowing your Credit Bureau important?",
"entities": [
{
"entity_value": "Credit Bureau",
"entity_type": "Fin_Corp",
"start_index": 20,
"end_index": 33,
}
],
},
{
"context": "Please explain what you mean by Qualifying Ratios .",
"entities": [
{
"entity_value": "Qualifying Ratios",
"entity_type": "Fin_Corp",
"start_index": 32,
"end_index": 49,
}
],
},
{
"context": "Please explain what you mean by Closed-Ended Credit .",
"entities": [
{
"entity_value": "Closed-Ended Credit",
"entity_type": "Fin_Corp",
"start_index": 32,
"end_index": 51,
}
],
},
{
"context": "please explain what is VA Loan in detail.",
"entities": [
{
"entity_value": "VA Loan",
"entity_type": "Fin_Corp",
"start_index": 23,
"end_index": 30,
}
],
},
{
"context": "please explain what is Agent in detail.",
"entities": [
{
"entity_value": "Agent",
"entity_type": "Fin_Corp",
"start_index": 23,
"end_index": 28,
}
],
},
{
"context": "Could you please elaborate Lease-Purchase ?",
"entities": [
{
"entity_value": "Lease-Purchase",
"entity_type": "Fin_Corp",
"start_index": 27,
"end_index": 41,
}
],
},
{
"context": "Could you please elaborate Interest Rate ?",
"entities": [
{
"entity_value": "Interest Rate",
"entity_type": "Fin_Corp",
"start_index": 27,
"end_index": 40,
}
],
},
{
"context": "Can you explain Delinquency to me?",
"entities": [
{
"entity_value": "Delinquency",
"entity_type": "Fin_Corp",
"start_index": 16,
"end_index": 27,
}
],
},
{
"context": "Can you explain Balloon Mortgage to me?",
"entities": [
{
"entity_value": "Balloon Mortgage",
"entity_type": "Fin_Corp",
"start_index": 16,
"end_index": 32,
}
],
},
{
"context": "what does Prepaid Items really mean",
"entities": [
{
"entity_value": "Prepaid Items",
"entity_type": "Fin_Corp",
"start_index": 10,
"end_index": 23,
}
],
},
{
"context": "what does Loan-to-Value Ratio really mean",
"entities": [
{
"entity_value": "Loan-to-Value Ratio",
"entity_type": "Fin_Corp",
"start_index": 10,
"end_index": 29,
}
],
},
{
"context": "Can you explain to me,please,what Homeowners Warranty Program means,what it applies to,what is its purpose? Thank you",
"entities": [
{
"entity_value": "Homeowners Warranty Program",
"entity_type": "Fin_Corp",
"start_index": 34,
"end_index": 61,
}
],
},
{
"context": "Can you explain to me,please,what Balloon Mortgage means,what it applies to,what is its purpose? Thank you",
"entities": [
{
"entity_value": "Balloon Mortgage",
"entity_type": "Fin_Corp",
"start_index": 34,
"end_index": 50,
}
],
},
{
"context": "what's the meaning of Mortgagee and how can i use it?",
"entities": [
{
"entity_value": "Mortgagee",
"entity_type": "Fin_Corp",
"start_index": 22,
"end_index": 31,
}
],
},
{
"context": "what's the meaning of Prepayment Penalty and how can i use it?",
"entities": [
{
"entity_value": "Prepayment Penalty",
"entity_type": "Fin_Corp",
"start_index": 22,
"end_index": 40,
}
],
},
{
"context": "Ive not heard that before. What does Interest Cap mean?",
"entities": [
{
"entity_value": "Interest Cap",
"entity_type": "Fin_Corp",
"start_index": 37,
"end_index": 49,
}
],
},
{
"context": "Ive not heard that before. What does Lender mean?",
"entities": [
{
"entity_value": "Lender",
"entity_type": "Fin_Corp",
"start_index": 37,
"end_index": 43,
}
],
},
{
"context": "Can you elaborate on what Mortgage Banker is about?",
"entities": [
{
"entity_value": "Mortgage Banker",
"entity_type": "Fin_Corp",
"start_index": 26,
"end_index": 41,
}
],
},
{
"context": "Can you elaborate on what Assessment is about?",
"entities": [
{
"entity_value": "Assessment",
"entity_type": "Fin_Corp",
"start_index": 26,
"end_index": 36,
}
],
},
{
"context": "I've never heard of Due-on-Sale , can you explain it to me in an easy way for me to understand?",
"entities": [
{
"entity_value": "Due-on-Sale",
"entity_type": "Fin_Corp",
"start_index": 20,
"end_index": 31,
}
],
},
{
"context": "I've never heard of Trust , can you explain it to me in an easy way for me to understand?",
"entities": [
{
"entity_value": "Trust",
"entity_type": "Fin_Corp",
"start_index": 20,
"end_index": 25,
}
],
},
{
"context": "How does my Market Value effect me?",
"entities": [
{
"entity_value": "Market Value",
"entity_type": "Fin_Corp",
"start_index": 12,
"end_index": 24,
}
],
},
{
"context": "How does my Balloon Mortgage effect me?",
"entities": [
{
"entity_value": "Balloon Mortgage",
"entity_type": "Fin_Corp",
"start_index": 12,
"end_index": 28,
}
],
},
]
|
# -*- coding: utf-8 -*-
"""Modulo helpers.url"""
def split_query_string(items):
"""dividir un query string"""
params = {'filter': {}, 'fields': [], 'pagination': {}, 'sort': {}, 'filter_in': {}}
for key, value in items:
sub_keys = key.split('.')
if 'fields' in sub_keys:
params['fields'] = [value] if isinstance(value, str) else value
elif sub_keys[0] in params:
params[sub_keys[0]].update({sub_keys[1]: value})
params['filter_in'] = get_filter_in(params['filter'])
params['sort'] = \
', '.join("{0} {1}".format(key, val.upper()) for (key, val) in params['sort'].items())
if params['pagination']:
params['pagination']['page'] = \
int(params['pagination']['page']) if 'page' in params['pagination'] else 1
params['pagination']['limit'] = \
int(params['pagination']['limit']) if 'limit' in params['pagination'] else 100
params['pagination'].update({
'offset':
(params['pagination']['page'] * \
params['pagination']['limit']) - \
params['pagination']['limit']
})
return params
def join_query_string():
"""Unir parametros en query string"""
pass
def get_filter_in(filters):
"""Recuperar filtros de una lista"""
filter_in = {}
for filter_index, value in list(filters.items()):
if isinstance(value, list):
filter_in.update({filter_index: value})
del filters[filter_index]
return filter_in
|
def entrance():
'''This is the initial room the player will begin their adventure.'''
pass
def orange_rm_1():
'''Todo:
red key(hidden in desk drawer)
health(desk top)
desk
rat (24% damage)
red door
'''
pass
def red_rm_2():
'''locked entrance- requires red key
to do:
skull of meatboy (20 questions)
bamboo (blowgun)
desk
dr. fetus (1% dmg atk, runs away after attack. mentions hidden passage)
'''
pass
def blue_rm_1():
'''to do list:
book case (hidden passage)
health (25%)
shield (50% damage decrease)
'''
pass
def blue_rm_2():
'''to do list:
axe for boss fight
red key (bowl)
locked orange door (to main boss)
'''
pass
def red_rm_1():
'''to do list:
door into room is locked (orange key hidden in red_rm_1)
note from file
dart
bread (inv - must use)
'''
pass
def red_rm_3():
'''to do list:
stick (weapon)
health (25%)
'''
pass
def red_rm_4():
'''banquet hall
table
food (invokes rat to attack if eaten/taken)
rat (24% dmg atk)
chair
'''
pass
def giant_toddler():
'''nursery atmosphere
to do:
giant toddler
rattle
boss room key
'''
pass
def watermelon_rex():
'''den of whoever runs this mad house
pink key
health
animal heads on walls (interactive - one head breaks upon engaging boss)
watermelon_rex
fire place
giant mahogany desk
'''
pass
|
def main(request, response):
headers = [("Content-Type", "text/javascript")]
milk = request.cookies.first("milk", None)
if milk is None:
return headers, "var included = false;"
elif milk.value == "yes":
return headers, "var included = true;"
return headers, "var included = false;"
|
"""
Tema: Algoritmo de aproximacion.
Curso: Pensamiento computacional.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
objetivo = int(input('Escoge un numero: '))
epsilon = 0.0001
paso = epsilon**2
respuesta = 0.0
while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo:
print(abs(respuesta**2 - objetivo), respuesta)
respuesta += paso
if abs(respuesta**2 - objetivo) >= epsilon:
print(f'No se encontro la raiz cuadrada {objetivo}')
else:
print(f'La raiz cudrada de {objetivo} es {respuesta}')
|
#!/usr/bin/python3.8
def nics_menu():
FILENAME = "nics.yaml"
SWITCHES = "-n/--nics"
DESCRIPTION = "YAML file that contains the configuration for the interfaces to use"
REQUIRED = "always"
TEMPLATE = """nics: # number of nics needs to equal to 2
"""
NIC_TEMPLATE = """ - name: "{}" # name of the interface
subnet: "{}" # IPv4 subnet in CIDR notation
subnet_v6: "{}" # IPv6 subnet in CIDR notation
gateway: "{}" # default IPv4 gateway
gateway_v6: "{}" # default IPv6 gateway
last_bytes_v6: 0x{} # last bytes of the random ip addresses used ; Needs to match at least the last 3 bytes of an IPv6 address assigned to this interface (only if promiscuous mode is not enabled, otherwise this can be whatever)
"""
print("Switches: " + SWITCHES)
print("Description: " + DESCRIPTION)
print("Required when: " + REQUIRED)
filename = input("filename? (default='{}'): ".format(FILENAME))
if not filename:
filename = FILENAME
config_content = TEMPLATE
for i in range(2):
name = input("nic #{} interface name?: ".format(i+1))
subnetv4 = input("nic #{} ipv4 subnet? (10.2.3.4/16): ".format(i+1))
subnetv6 = input("nic #{} ipv6 subnet? (fe80::aaaa:bbbb/64): ".format(i+1))
gatewayv4 = input("nic #{} ipv4 gateway? (10.2.3.4): ".format(i+1))
gatewayv6 = input("nic #{} ipv6 gateway? (fe80::aaaa:bbbb): ".format(i+1))
prom_mode = input("does the network for nic #{} support promiscuous mode? (Y/N): ".format(i+1))
last6 = ""
if prom_mode == "N":
last6 = input("last 3 bytes of an IPv6 address assigned to nic #{}? (dead12): ".format(i + 1))
else:
last6 = "000000"
nici = NIC_TEMPLATE.format(name, subnetv4, subnetv6, gatewayv4, gatewayv6, last6)
config_content += nici
with open(filename, "w") as f:
f.write(config_content)
print("[+] saved {}".format(filename))
def blacklist_menu():
FILENAME = "blacklist.yaml"
SWITCHES = "-b/--blacklist"
DESCRIPTION = "YAML file that contains other hosts on the network to blacklist (excludes gateways)"
REQUIRED = "--ccm FiveTuple is not specified. Note that if there is UDP/TCP proxy inline --ccm FiveTuple MUST NOT be specified when a connection's 5-tuples differ on either side of the proxy"
print("Switches: " + SWITCHES)
print("Description: " + DESCRIPTION)
print("Required when: " + REQUIRED)
filename = input("filename? (default='{}'): ".format(FILENAME))
if not filename:
filename = FILENAME
config_content = "--\n"
print("Enter mac addresses to blacklist. Don't enter the address of the gateway(s)")
print("Enter '0' to stop")
config_content += "mac:\n"
while True:
addr = input("mac address? (00:50:56:aa:bb:cc): ")
if addr == '0':
break
if addr == '':
continue
config_content += ' - "{}"\n'.format(addr)
print("Enter IPv4 addresses to blacklist. Don't enter the address(es) of the gateway(s)")
print("Enter '0' to stop")
config_content += "ipv4:\n"
while True:
addr = input("ipv4 address? (10.2.3.4): ")
if addr == '0':
break
if addr == '':
continue
config_content += ' - "{}"\n'.format(addr)
print("Enter IPv6 addresses to blacklist. Don't enter the address(es) of the gateway(s)")
print("Enter '0' to stop")
config_content += "ipv6:\n"
while True:
addr = input("ipv6 address? (fe80::aaaa:bbbb): ")
if addr == '0':
break
if addr == '':
continue
config_content += ' - "{}"\n'.format(addr)
with open(filename, "w") as f:
f.write(config_content)
print("[+] saved {}".format(filename))
def modes_menu():
FILENAME = "modes.csv"
SWITCHES = "-m/--modes"
DESCRIPTION = "CSV file that contains mode exceptions (min & max) on a per pcap basis"
REQUIRED = "a pcap should be replayed in a mode that differs from the mode specified with -dm/--dmode"
print("Switches: " + SWITCHES)
print("Description: " + DESCRIPTION)
print("Required when: " + REQUIRED)
filename = input("filename? (default='{}'): ".format(FILENAME))
if not filename:
filename = FILENAME
config_content = ""
while True:
pcap_name = input("pcap_name? (example.pcap): ")
min_mode = input("min mode? (L3/L4/L5): ")
max_mode = input("max mode? (L3/L4/L5): ")
entry = ",".join([pcap_name, min_mode, max_mode])
config_content += entry + "\n"
more_exceptions = input("Any more exceptions? (Y/N): ")
if more_exceptions == "N":
break
with open(filename, "w") as f:
f.write(config_content)
print("[+] saved {}".format(filename))
def main_menu():
print("Main Menu:")
print("1. nics file (-n/--nics)")
print("2. blacklist file (-b/--blacklist)")
print("3. modes file (-m/--modes)")
choice = input("Please make a choice: ")
if choice == "1":
nics_menu()
elif choice == "2":
blacklist_menu()
elif choice == "3":
modes_menu()
main_menu()
if __name__ == '__main__':
main_menu()
|
"""Amazon Product Advertising API wrapper for Python"""
__version__ = '3.2.0'
__author__ = 'Sergio Abad'
|
"""
My first Python script
- this is a multiline comment
"""
# My second comment
'''
This is also a multiline comment
'''
statement = 0
if statement !=False:
print(4)
counter = 1000
count = 0
sum = 0
while count < counter:
if count%3 ==0:
sum = sum+count
elif count%5 ==0:
sum = sum+count
count = count +1
print(sum)
|
for i in range(int(input())):
H, W ,N = map(int,input().split())
temp = N
tmp = 1
#층
if N%H == 0:
temp = H
else:
temp = N%H
#호수
if N/H > int(N/H):
tmp = int(N/H)+1
else:
tmp = int(N/H)
if tmp < 10:
print(temp,"0",tmp,sep="")
else:
print(temp,tmp,sep="")
|
localizacao = {'Brasil': 'América',
'Portugal': 'Europa',
'Espanha': 'Europa'}
continente_brasil = localizacao['Brasil']
print(continente_brasil)
|
CORRECT_PIN = "1234"
MAX_TRIES = 3
tries_left = MAX_TRIES
pin = input(f"Insert your pni ({tries_left} tries left): ")
while tries_left > 1 and pin != CORRECT_PIN:
tries_left -= 1
print("Your PIN is incorrect.")
pin = input(f"Insert your pni ({tries_left} tries left): ")
if pin == CORRECT_PIN:
print("Your PIN is correct")
else:
print("Your bank card is blocked")
|
#
# Solution to Project Euler problem 73
# Copyright (c) Project Nayuki. All rights reserved.
#
# https://www.nayuki.io/page/project-euler-solutions
# https://github.com/nayuki/Project-Euler-solutions
#
# The Stern-Brocot tree is an infinite binary search tree of all positive rational numbers,
# where each number appears only once and is in lowest terms.
# It is formed by starting with the two sentinels 0/1 and 1/1. Iterating infinitely in any order,
# between any two currently adjacent fractions Ln/Ld and Rn/Rd, insert a new fraction (Ln+Rn)/(Ld+Rd).
# See MathWorld for a visualization: http://mathworld.wolfram.com/Stern-BrocotTree.html
#
# The natural algorithm is as follows:
# # Counts the number of reduced fractions n/d such that leftN/leftD < n/d < rightN/rightD and d <= 12000.
# # leftN/leftD and rightN/rightD must be adjacent in the Stern-Brocot tree at some point in the generation process.
# def stern_brocot_count(leftn, leftd, rightn, rightd):
# d = leftd + rightd
# if d > 12000:
# return 0
# else:
# n = leftn + rightn
# return 1 + stern_brocot_count(leftn, leftd, n, d) + stern_brocot_count(n, d, rightn, rightd)
# But instead we use depth-first search on an explicit stack, because having
# a large number of stack frames seems to be supported on Linux but not on Windows.
def compute():
ans = 0
stack = [(1, 3, 1, 2)]
while len(stack) > 0:
leftn, leftd, rightn, rightd = stack.pop()
d = leftd + rightd
if d <= 12000:
n = leftn + rightn
ans += 1
stack.append((n, d, rightn, rightd))
stack.append((leftn, leftd, n, d))
return str(ans)
if __name__ == "__main__":
print(compute())
|
"""
Contains the Artist class
"""
__all__ = [
'Artist',
]
class Artist(object):
"""
Represents an artist
"""
def __init__(self):
"""
Initiate properties
"""
self.identifier = 0
self.name = ''
self.other_names = ''
self.group_name = ''
self.urls = ''
self.is_active = False
self.version = 0
self.updater_id = 0
def __str__(self):
"""
String representation of the object
"""
return 'Artist<{}>'.format(self.identifier)
|
class BaseSiteCheckerException(Exception):
pass
class ErrorStopMsgLimit(BaseSiteCheckerException):
pass
|
def get_safe_balanced_split(target, train_ratio=0.8, get_test_indices=True, shuffle=False, seed=None):
classes, counts = np.unique(target, return_counts=True)
num_per_class = float(len(target))*float(train_ratio)/float(len(classes))
if num_per_class > np.min(counts):
print("Insufficient data to produce a balanced training data split.")
print("Classes found {}".format(classes))
print("Classes count {}".format(counts))
ts = float(train_ratio*np.min(counts)*len(classes)) / float(len(target))
print("train_ratio is reset from {} to {}".format(train_ratio, ts))
train_ratio = ts
num_per_class = float(len(target))*float(train_ratio)/float(len(classes))
num_per_class = int(num_per_class)
print("Data splitting on {} classes and returning {} per class".format(len(classes), num_per_class ))
# get indices
train_indices = []
for c in classes:
if seed is not None:
np.random.seed(seed)
c_idxs = np.where(target==c)[0]
c_idxs = np.random.choice(c_idxs, num_per_class, replace=False)
train_indices.extend(c_idxs)
# get test indices
test_indices = None
if get_test_indices:
test_indices = list(set(range(len(target))) - set(train_indices))
# shuffle
if shuffle:
train_indices = random.shuffle(train_indices)
if test_indices is not None:
test_indices = random.shuffle(test_indices)
return train_indices, test_indices
|
print("Welcome to the Multiplication/Exponent Table App")
print()
name = input("Hello, What is your name: ")
number = float(input("What number would you like to work with: "))
name = name.strip()
print("Multiplication Table For {}".format(number))
print()
print("\t\t1.0 * {} = {:.2f}".format(number, number*1.0))
print("\t\t2.0 * {} = {:.2f}".format(number, number*2.0))
print("\t\t3.0 * {} = {:.2f}".format(number, number*3.0))
print("\t\t4.0 * {} = {:.2f}".format(number, number*4.0))
print("\t\t5.0 * {} = {:.2f}".format(number, number*5.0))
print("\t\t6.0 * {} = {:.2f}".format(number, number*6.0))
print("\t\t7.0 * {} = {:.2f}".format(number, number*7.0))
print("\t\t8.0 * {} = {:.2f}".format(number, number*8.0))
print("\t\t9.0 * {} = {:.2f}".format(number, number*9.0))
print()
print("Exponent Table For {}".format(number))
print()
print("\t\t{} ** 1 = {:.2f}".format(number, number**1))
print("\t\t{} ** 2 = {:.2f}".format(number, number**2))
print("\t\t{} ** 3 = {:.2f}".format(number, number**3))
print("\t\t{} ** 4 = {:.2f}".format(number, number**4))
print("\t\t{} ** 5 = {:.2f}".format(number, number**5))
print("\t\t{} ** 6 = {:.2f}".format(number, number**6))
print("\t\t{} ** 7 = {:.2f}".format(number, number**7))
print("\t\t{} ** 8 = {:.2f}".format(number, number**8))
print("\t\t{} ** 9 = {:.2f}".format(number, number**9))
print()
message = "{} Math is cool!".format(name)
print(message)
print("\t{}".format(message.lower()))
print("\t\t{}".format(message.title()))
print("\t\t\t{}".format(message.lower()))
|
# Live preview Markdown and reStructuredText files as HTML in a web browser.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: April 12, 2018
# URL: https://github.com/xolox/python-preview-markup
__version__ = '0.3.3'
|
class DockablePaneState(object,IDisposable):
"""
Describes where a dockable pane window should appear in the Revit user interface.
DockablePaneState(other: DockablePaneState)
DockablePaneState()
"""
def Dispose(self):
""" Dispose(self: DockablePaneState) """
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: DockablePaneState,disposing: bool) """
pass
def SetFloatingRectangle(self,rect):
"""
SetFloatingRectangle(self: DockablePaneState,rect: Rectangle)
When %dockPosition% is Floating,sets the rectangle used to determine the size
and position of the pane when %dockPosition% is Floating. Coordinates are
relative to the upper-left-hand corner of the main Revit window.
"""
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,other=None):
"""
__new__(cls: type,other: DockablePaneState)
__new__(cls: type)
"""
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
DockPosition=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Which part of the Revit application frame the pane should dock to.
Get: DockPosition(self: DockablePaneState) -> DockPosition
Set: DockPosition(self: DockablePaneState)=value
"""
FloatingRectangle=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""When %dockPosition% is Floating,this rectangle determines the size and position of the pane. Coordinates are relative to the upper-left-hand corner of the main Revit window.
Note: the returned Rectangle is a copy. In order to change the pane state,you must call SetFloatingRectangle with a modified rectangle.
Get: FloatingRectangle(self: DockablePaneState) -> Rectangle
"""
IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Specifies whether the .NET object represents a valid Revit entity.
Get: IsValidObject(self: DockablePaneState) -> bool
"""
TabBehind=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Ignored unless %dockPosition% is Tabbed. The new pane will appear in a tab behind the specified existing pane ID.
Get: TabBehind(self: DockablePaneState) -> DockablePaneId
Set: TabBehind(self: DockablePaneState)=value
"""
|
class Solution:
"""
@param n: an integer
@return: if n is a power of two
"""
def isPowerOfTwo(self, n):
# Write your code here
while n>1:
n=n/2
if n ==1:
return True
else:
return False
|
#
# These methods are working on multiple processors
# that can be located remotely
#
class Bridges:
@staticmethod
def create(master=None, workers=None, name=None):
raise NotImplementedError
@staticmethod
def set(master=None, workers=None, name=None):
raise NotImplementedError
@staticmethod
def list(hosts=None):
raise NotImplementedError
@staticmethod
def check(hosts=None):
raise NotImplementedError
@staticmethod
def restart(host=None):
raise NotImplementedError
|
#Crie um programa que leia dois números e mostre a soma entre eles.
while True:
try:
sValue1 = input('Digite o primeiro número:')
sValue2 = input('Digite o segundo número:')
fValue1 = float(sValue1)
fValue2 = float(sValue2)
except:
print('Digite apenas valores numéricos!')
else:
break
print(f'A soma entre {fValue1} e {fValue2} é {fValue1 + fValue2}')
|
"""Simple touch utility."""
def touch(filename: str) -> None:
"""Mimics the "touch filename" utility.
:param filename: filename to touch
"""
with open(filename, "a"):
pass
|
for index in range(1,101):
# if index % 15 == 0:
# print("fifteen")
if index % 3 == 0 and index % 5 == 0 :
print("fifteen")
elif index % 3 == 0:
print("three")
elif index % 5 == 0:
print("five")
else:
print(index)
|
class Solution:
def rob(self, nums):
if not nums:
return 0
values = [0] * len(nums)
for i in range(len(nums)):
if i == 0:
values[i] = max(values[i], nums[i])
elif i == 1:
values[i] = max(values[i-1], nums[i])
else:
values[i] = max(values[i-2] + nums[i], values[i-1])
return values[-1]
s = Solution()
print(s.rob([2,7,9,3,1]))
|
# Copyright 2018 The TensorFlow Authors.
#
# 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.
"""Postprocessing utility function for CLIF."""
# CLIF postprocessor for a C++ function with signature:
# bool MyFunc(input_arg1, ..., *output_arg1, *output_arg2, ..., *error)
#
# If MyFunc returns True, returns (output_arg1, output_arg2, ...)
# If MyFunc returns False, raises ValueError(error).
def ValueErrorOnFalse(ok, *output_args):
"""Raises ValueError if not ok, otherwise returns the output arguments."""
n_outputs = len(output_args)
if n_outputs < 2:
raise ValueError("Expected 2 or more output_args. Got: %d" % n_outputs)
if not ok:
error = output_args[-1]
raise ValueError(error)
if n_outputs == 2:
output = output_args[0]
else:
output = output_args[0:-1]
return output
# CLIF postprocessor for a C++ function with signature:
# *result MyFactory(input_arg1, ..., *error)
#
# If result is not null, returns result.
# If result is null, raises ValueError(error).
def ValueErrorOnNull(result, error):
"""Raises ValueError(error) if result is None, otherwise returns result."""
if result is None:
raise ValueError(error)
return result
|
MASTER_PROCESS_RANK = 0 # Only meaningful if webscraper is run with multiple processes. Here we use rank = 0 for master process; however we can set it to any value in [0, nprocs-1].
READING_RATIO_FOR_INPUT_CSVs = 1 # It represents how much of the input files (in csv format for now) we should process. MUST BE BETWEEN [0, 1]. For example 0.1 means; process 1/10th of each of the input files (in terms of rows) and 1 means read them all.
NUMBER_OF_REPEATS_TIMEIT = 1
CREATE_WORD_CLOUD = True
CREATE_BAG_OF_WORDS = True
CREATE_SENTIMENT_ANALYSIS_RESULTS = True
|
#
# @lc app=leetcode.cn id=1689 lang=python3
#
# [1689] detect-pattern-of-length-m-repeated-k-or-more-times
#
None
# @lc code=end
|
print("Raadsel 1:",
"\n Wanneer leefde de oudste persoon ter wereld?")
guess = input() #"TUSSEN GEBOORTE en dood" # input ()
guess_words = []
for g in guess.split():
guess_words.append(g.lower())
answer_words = ["tussen", "geboorte", "dood"]
incorrect = False
for word in answer_words:
if word not in guess_words:
incorrect = True
if incorrect == True:
print ("Jammer, je hebt het fout geraden,",
"het antwoord was \n tussen zijn geboorte en zijn dood")
else:
print ("Goed gedaan, je hebt het geraden.")
|
class SettingsCalibration:
"""Период калибровки"""
first_period = 0 # ПК1
second_period = 1 # ПК2
third_period = 2 # ПК3
periods = {
first_period: 1,
second_period: 2,
third_period: 60,
}
class SettingsSpaceCycles:
"""Число циклов космоса"""
cos1 = 0 # КОС1
cos2 = 1 # КОС2
cycles = {
cos1: 2,
cos2: 30,
}
class SettingsBlackBodyCycles:
"""Число циклов абсолютно черного тела (АЧТ)"""
abb1 = 0 # АЧТ1
abb2 = 1 # АЧТ2
cycles = {
abb1: 2,
abb2: 30,
}
class SettingsLane:
"""Полоса обзора"""
first = 0 # ПО1
second = 1 # ПО2
third = 2 # ПО3
fourth = 3 # ПО4
class SettingsGain:
"""Коэффициент усиления"""
gain1 = 0 # КУ1
gain2 = 1 # КУ2
gain3 = 2 # КУ3
class SettingsInterferometerModule:
"""Температура модуля интерферометра (МИ)"""
tim1 = 0 # ТМИ1
tim2 = 1 # ТМИ2
tim3 = 2 # ТМИ3
temperatures = {
tim1: 20.,
tim2: 18.,
tim3: 15.,
}
|
def wczytaj():
"""
Wczytanie danych z pliku do tabeli
returns list of strings
"""
tab = []
with open("liczby.txt", "r") as f:
for line in f:
#print(line.strip())
tab.append(line.strip())
#print(tab)
return tab
def podpunkt1(tab):
suma = 0
for liczba in tab:
#print(f"{liczba.count('0')} ? {liczba.count('1')}")
if liczba.count('0') > liczba.count('1'):
suma +=1
return suma
def podpunkt2(tab):
suma1, suma2 = 0, 0
for liczba in tab:
a = int(liczba, 2)
if a % 2 == 0:
suma1 +=1
if a % 8 == 0:
suma2 +=1
return suma1, suma2
def podpunkt3(tab : list[str]) :
liczby = [int(i, 2) for i in tab] # list comprehension zamiana stringów binarnych na int
print(liczby)
return liczby.index(max(liczby)) + 1, liczby.index(min(liczby)) +1
def main():
liczby = wczytaj()
#suma1 = podpunkt1(liczby)
with open("wynik4.txt", 'w') as f:
f.write(f"4.1 {podpunkt1(liczby)}\n4.2 {podpunkt2(liczby)}\n4.3 {podpunkt3(liczby)}")
print(f"{podpunkt1(liczby)}\n{podpunkt2(liczby)}\n{podpunkt3(liczby)}")
if __name__ == '__main__':
main()
|
# Problem code
def countAndSay(n):
if n == 1:
return "1"
current = "1"
for i in range(2, n + 1):
current = helper(current)
return current
def helper(current):
group_count = 1
group_member = current[0]
result = ""
for i in range(1, len(current)):
if current[i] == group_member:
group_count += 1
continue
else:
result += str(group_count)
result += str(group_member)
group_count = 1
group_member = current[i]
result += str(group_count)
result += str(group_member)
return result
# Setup
print(countAndSay(4))
|
"""
This package contains serializers. Purpose of serializer class
is to convert hwt representations of designed architecture
to target language or form (VHDL/Verilog/SystemC...).
"""
|
# A classroom consists of N students, whose friendships can be represented in
# an adjacency list. For example, the following descibes a situation where 0
# is friends with 1 and 2, 3 is friends with 6, and so on.
# {0: [1, 2],
# 1: [0, 5],
# 2: [0],
# 3: [6],
# 4: [],
# 5: [1],
# 6: [3]}
# Each student can be placed in a friend group, which can be defined as the
# transitive closure of that student's friendship relations. In other words,
# this is the smallest set such that no student in the group has any friends
# outside this group. For the example above, the friend groups would be
# {0, 1, 2, 5}, {3, 6}, {4}.
# Given a friendship list such as the one above, determine the number of
# friend groups in the class.
def friend_group(adjacency):
groups = []
mapping = {}
for i in adjacency:
if i in mapping:
continue
for adj in adjacency[i]:
if adj in mapping:
groups[mapping[adj]].add(i)
mapping[i] = mapping[adj]
if i not in mapping:
mapping[i] = len(groups)
groups.append({i})
return groups
if __name__ == '__main__':
print(friend_group({
0: [1, 2],
1: [0, 5],
2: [0],
3: [6],
4: [],
5: [1],
6: [3]
}))
|
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
if not text1 or not text2:
return 0
m = len(text1)
n = len(text2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if text1[i-1] == text2[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
return dp[m][n]
|
class Printer(object):
def __init__(self, sort_keys=None, order=None, header=None):
self.sort_keys = sort_keys
self.order = order
self.header = header
def print(self, d, format='table'):
print(self.value(d,format=format))
def value(self, d, format='table'):
return Printer.flatwrite(
d,
sort_keys=self.keys,
order=self.order,
header=self.header
)
|
# Copyright 2020 BlueCat Networks. All rights reserved.
# -*- coding: utf-8 -*-
type = 'api'
sub_pages = [
{
'name' : 'user_inventory_page',
'title' : u'user_inventory',
'endpoint' : 'user_inventory/user_inventory_endpoint',
'description' : u'user_inventory'
},
]
|
"""
One way of improving the memory efficiency of the NaiveStack would be to recognise that:
[]
[1]
[1,2]
[1,2,3]
Holds the same information as:
[1, 2, 3]
(on the assumption that there have been no pops)
So rather than creating a new version for every push and every pop, we could create a new version only on pops,
since it is easy to see what the previous version of a stack that has been pushed to was.
This does mean that finding a particular version would no longer be a simple index look-up. You'd need
to iterate through each version until you found the right one.
Rather than storing a copy of each version, perhaps it would be more memory efficient to store
the sequence of update operations. And when a particular version is asked for, we could then
re-create that particular version from scratch? This would come at a cost for reading.
Each read would require all the update operations to be re-run first.
One solution to this might be to store a) the most recently accessed version r, and
b) the sequence of update operations, and c) to make sure all update operations are reversible.
Then, if we want to read from version v, rather than iterating through update operations
from 0 to v, we could find the 'fastest path' either forwards or backwards from r to v.
A stack is readily reversible. The reverse of a push is a pop. And the reverse of a pop is to push its return value.
If we know the sequence of pushes and pops we can start at any point in that sequence and go back and forth in it.
Let's implement that as ReversibleStack.
"""
class NaiveStack:
""" A partially persistent stack that makes no effort to save space or time. """
def __init__(self):
self.stacks = [[]]
def push(self, value):
new_stack = self.stacks[-1].copy()
new_stack.append(value)
self.stacks.append(new_stack)
def pop(self):
new_stack = self.stacks[-1].copy()
value = new_stack.pop()
self.stacks.append(new_stack)
return value
def read(self, version, index):
return self.stacks[version][index]
def show(self):
for stack in self.stacks:
print(stack)
class SequenceStack:
""" A partially persistent stack that iterates through a subsequence of update operations
to return a given version. Saves space but slows down read operations."""
def __init__(self):
self.sequence = [] # the complete sequence of pushes and pops
def push(self, value):
"""Append a push operation to end of update sequence."""
self.sequence.append(lambda stack: stack.append(value))
def pop(self):
"""Append a pop operation to end of update sequence."""
self.sequence.append(lambda stack: stack.pop())
def read_version(self, version):
"""Return the stack as it was at version."""
stack = []
for update_operation in self.sequence[:version]:
update_operation(stack)
return stack
def read(self, version, index):
return self.read_version(version)[index]
def show(self):
""" Print all versions of the stack. """
for v in range(len(self.sequence)):
print("version {}: ".format(v), self.read_version(v))
class ReversibleSequenceStack:
""" A partially persistent stack that stores the most recently read version and
iterates either forwards or backwards through the sequence of update operations
to return a requested version. This saves on space (although doubles the space
requirements for storing update operations because we are saving both the original
and its reverse), and tries to make up for the slow reading operation by reducing
how many update operations must be applied to reach the desired version."""
def __init__(self):
self.sequence = [] # the complete sequence of pushes and pops
self.stack = [] # most recently read version of the stack
self.version = 0 # most recently read version
def push(self, value):
"""Append a tuple of push and pop operation to end of update sequence."""
# the second value of the tuple is the opposite and can be used to iterate backwards
op = lambda stack: stack.append(value)
rev_op = lambda stack: stack.pop()
self.sequence.append((op, rev_op))
def pop(self):
"""Append a tuple of pop and push operation to end of update sequence."""
# the second value of the tuple is the opposite and can be used to iterate backwards
value = self.read_version(len(self.sequence))[-1]
op = lambda stack: stack.pop()
rev_op = lambda stack: stack.append(value)
self.sequence.append((op, rev_op))
def read_version(self, version):
"""Return the stack as it was at version."""
if version == self.version: return self.stack
while self.version < version:
update_operation = self.sequence[self.version][0]
self.version += 1
update_operation(self.stack)
while self.version > version:
update_operation = self.sequence[self.version-1][1]
self.version -= 1
update_operation(self.stack)
return self.stack
def read(self, version, index):
return self.read_version(version)[index]
rs = ReversibleSequenceStack()
rs.push(1)
rs.push(2)
rs.push(3)
rs.pop()
rs.pop()
rs.push(7)
for i in range(0, 7):
print(i, rs.read_version(i))
for i in range(6, -1, -1):
print(i, rs.read_version(i))
|
__all__ = ("Values", )
class Data(object):
def __init__(
self,
plugin_instance=None,
meta=None,
plugin=None,
host=None,
type=None,
type_instance=None,
interval=None,
time=None,
values=None,
):
self.plugin = plugin
self.plugin_instance = plugin_instance,
self.meta = meta
self.host = host
self.type = type
self.type_instance = type_instance
self.dstypes = dstypes
self.values = values
self.interval = interval
self.time = time
def dispatch(self):
pass
def mk_values(
plugin_instance=None,
meta=None,
plugin=None,
host=None,
type=None,
type_instance=None,
interval=None,
time=None,
values=None,
):
return Data(
plugin_instance=plugin_instance,
meta=meta,
plugin=plugin,
host=host,
type=type,
type_instance=type_instance,
interval=interval,
time=time,
values=values,
)
Values = mk_values
|
age = 6
if age < 1:
print("baby")
elif age < 3:
print("toddler")
elif age < 5:
print("preschool")
elif age < 12:
print("gradeschooler")
elif age < 19:
print("teen")
elif age > 20:
print("old")
else:
print("integer error")
|
def main():
# input
H, W = map(int, input().split())
sss = [input() for _ in range(H)]
# compute
cnt = 0
for h in range(1,H-1):
for w in range(1,W-1):
if sss[h][w]=='#' and sss[h-1][w]!='#' and sss[h+1][w]!='#' and sss[h][w-1]!='#' and sss[h][w+1]!='#':
cnt += 1
# output
if cnt == 0:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
walle-web
:copyright: © 2015-2017 walle-web.io
:created time: 2018-11-11 19:49:37
:author: wushuiyong@walle-web.io
"""
class Code():
#: 1xxx 表示用户相关: 登录, 权限
#: 未登录, 大概是永远不会变了
unlogin = 1000
#: 无此权限
not_allow = 1001
#: 尚未开通空间
space_empty = 1002
#: 无此空间权限
space_error = 1003
#: 2xxx 表示参数错误
params_error = 2000
code_msg = {
unlogin: '未登录',
not_allow: '无此权限',
params_error: '参数错误',
space_empty: '尚未开通空间, 请联系空间负责人加入空间',
space_error: '无此空间权限',
}
|
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
arr = [0] * (length + 1)
for s, e, i in updates:
arr[s] += i
arr[e+1] -= i
for i in range(1, length):
arr[i] += arr[i-1]
return arr[:-1]
|
nerdle_len = 8
nerd_num_list = [str(x) for x in range(nerdle_len+2)]
nerd_op_list = ['+','-','*','/','==']
nerd_list = nerd_num_list+nerd_op_list
|
def assert_raises(excClass, callableObj, *args, **kwargs):
"""
Like unittest.TestCase.assertRaises, but returns the exception.
"""
try:
callableObj(*args, **kwargs)
except excClass as e:
return e
else:
if hasattr(excClass,'__name__'): excName = excClass.__name__
else: excName = str(excClass)
raise AssertionError("%s not raised" % excName)
|
'''
As is can shift max '1111' -> 15 on one command...
So a call like shift(20) would need to be split up...
Thinking the user should do this when coding... or
could be stdlib fx that does this...
If want to do shift(16) in one cycle, can add s4 support
(and correspoinding 16muxes) to hardware... revisit as needed
'''
def shiftRight16_( x, y ):
''' 16 bit barrel shifter (right) '''
N = 16
t0 = [ None ] * N
t1 = [ None ] * N
t2 = [ None ] * N
t3 = [ None ] * N
y = y[::-1] # make life simpler by matching array access to MSB-to-LSB format
#
for i in range( N - 1, 0, -1 ):
t0[i] = mux_( x[ i - 1 ], x[i], y[0] )
t0[0] = mux_( 0, x[0], y[0] )
#
for i in range( N - 1, 1, -1 ):
t1[i] = mux_( t0[ i - 2 ], t0[i], y[1] )
t1[1] = mux_( 0, t0[1], y[1] )
t1[0] = mux_( 0, t0[0], y[1] )
#
for i in range( N - 1, 3, -1 ):
t2[i] = mux_( t1[ i - 4 ], t1[i], y[2] )
t2[3] = mux_( 0, t1[3], y[2] )
t2[2] = mux_( 0, t1[2], y[2] )
t2[1] = mux_( 0, t1[1], y[2] )
t2[0] = mux_( 0, t1[0], y[2] )
#
for i in range( N - 1, 7, -1 ):
t3[i] = mux_( t2[ i - 8 ], t2[i], y[3] )
t3[7] = mux_( 0, t2[7], y[3] )
t3[6] = mux_( 0, t2[6], y[3] )
t3[5] = mux_( 0, t2[5], y[3] )
t3[4] = mux_( 0, t2[4], y[3] )
t3[3] = mux_( 0, t2[3], y[3] )
t3[2] = mux_( 0, t2[2], y[3] )
t3[1] = mux_( 0, t2[1], y[3] )
t3[0] = mux_( 0, t2[0], y[3] )
#
return t3
def shiftLeft16_( x, y ):
''' 16 bit barrel shifter (left) '''
N = 16
t0 = [ None ] * N
t1 = [ None ] * N
t2 = [ None ] * N
t3 = [ None ] * N
y = y[::-1] # make life simpler by matching array access to MSB-to-LSB format
#
t0[N - 1] = mux_( 0, x[N - 1], y[0] )
for i in range( N - 2, -1, -1 ):
t0[i] = mux_( x[ i + 1 ], x[i], y[0] )
#
t1[ N - 1 ] = mux_( 0, t0[ N - 1 ], y[1] )
t1[ N - 2 ] = mux_( 0, t0[ N - 2 ], y[1] )
for i in range( N - 3, -1, -1 ):
t1[i] = mux_( t0[ i + 2 ], t0[i], y[1] )
#
t2[ N - 1 ] = mux_( 0, t1[ N - 1 ], y[2] )
t2[ N - 2 ] = mux_( 0, t1[ N - 2 ], y[2] )
t2[ N - 3 ] = mux_( 0, t1[ N - 3 ], y[2] )
t2[ N - 4 ] = mux_( 0, t1[ N - 4 ], y[2] )
for i in range( N - 5, -1, -1 ):
t2[i] = mux_( t1[ i + 4 ], t1[i], y[2] )
#
t3[ N - 1 ] = mux_( 0, t2[ N - 1 ], y[3] )
t3[ N - 2 ] = mux_( 0, t2[ N - 2 ], y[3] )
t3[ N - 3 ] = mux_( 0, t2[ N - 3 ], y[3] )
t3[ N - 4 ] = mux_( 0, t2[ N - 4 ], y[3] )
t3[ N - 5 ] = mux_( 0, t2[ N - 5 ], y[3] )
t3[ N - 6 ] = mux_( 0, t2[ N - 6 ], y[3] )
t3[ N - 7 ] = mux_( 0, t2[ N - 7 ], y[3] )
t3[ N - 8 ] = mux_( 0, t2[ N - 8 ], y[3] )
for i in range( N - 9, -1, -1 ):
t3[i] = mux_( t2[ i + 8 ], t2[i], y[3] )
#
return t3
|
# coding: utf-8
SECRET_KEY = 'foo'
EMAIL_BACKEND = 'postmarker.django.EmailBackend'
POSTMARK = {
'TOKEN': '<YOUR POSTMARK SERVER TOKEN>'
}
|
def is_prime(num, primes):
for prime in primes:
if prime == num:
return True
if not num % prime:
return False
return True
def get_primes(num):
limit = (num // 2) + 1
candidates = list()
primes = list()
for i in range(2, limit):
if is_prime(i, primes):
primes.append(i)
candidates.append((i, num - i))
new_candidates = list()
for first, second in candidates[::-1]:
if is_prime(second, primes):
primes.append(second)
new_candidates.append((first, second))
return new_candidates[-1]
assert get_primes(4) == (2, 2)
assert get_primes(10) == (3, 7)
assert get_primes(100) == (3, 97)
|
#program to remove two duplicate numbers from a given number of list.
def two_unique_nums(nums):
return [i for i in nums if nums.count(i)==1]
print(two_unique_nums([1,2,3,2,3,4,5]))
print(two_unique_nums([1,2,3,2,4,5]))
print(two_unique_nums([1,2,3,4,5]))
|
types = [
{
'name': 'RNAExpression',
'item_type': 'rna-expression',
'schema': {
'title': 'RNAExpression',
'description': 'Schema for RNA-seq expression',
'properties': {
'uuid': {
'title': 'UUID',
},
'expression': {
'type': 'object',
'properties': {
'gene_id': {
'title': 'Gene ID',
'type': 'string'
},
'transcript_ids': {
'title': 'Transcript ID',
'type': 'string'
},
'tpm': {
'title': 'TPM',
'type': 'float'
},
'fpkm': {
'title': 'FPKM',
'type': 'float'
}
}
},
'file': {
'type': 'object',
'properties': {
'@id': {
'type': 'string'
},
'assay_title': {
'title': 'Assay title',
'type': 'string'
},
'assembly': {
'title': 'Assembly',
'type': 'string'
},
'biosample_ontology': {
'type': 'object',
'properties': {
'organ_slims': {
'type': 'string'
},
'term_name': {
'type': 'string'
},
'synonyms': {
'type': 'string'
},
'name': {
'type': 'string'
},
'term_id': {
'type': 'string'
},
'classification': {
'type': 'string'
}
}
},
'dataset': {
'type': 'string'
},
'donors': {
'type': 'string'
},
'genome_annotation': {
'type': 'string'
}
}
},
'dataset': {
'type': 'object',
'properties': {
'@id': {
'type': 'string'
},
'biosample_summary': {
'type': 'string'
},
'replicates': {
'type': 'object',
'properties': {
'library': {
'type': 'object',
'properties': {
'biosample': {
'type': 'object',
'properties': {
'age_units': {
'type': 'string'
},
'sex': {
'type': 'string'
},
'age': {
'type': 'string'
},
'donor': {
'type': 'object',
'properties': {
'organism': {
'type': 'object',
'properties': {
'scientific_name': {
'type': 'string'
}
}
}
}
}
}
}
}
}
}
}
}
},
'gene': {
'type': 'object',
'properties': {
'geneid': {
'type': 'string'
},
'symbol': {
'type': 'string'
},
'name': {
'type': 'string'
},
'synonyms': {
'type': 'string'
},
'@id': {
'type': 'string'
},
'title': {
'type': 'string'
}
}
},
'@id': {
'title': 'ID',
'type': 'string',
},
'@type': {
'title': 'Type',
'type': 'array',
'items': {
'type': 'string'
},
}
},
'columns': {
'expression.gene_id': {
'title': 'Feature ID'
},
'expression.tpm': {
'title': 'TPM'
},
'expression.fpkm': {
'title': 'FPKM'
},
'gene.symbol': {
'title': 'Gene symbol'
},
'gene.name': {
'title': 'Gene name'
},
'gene.title': {
'title': 'Gene title'
},
'file.biosample_ontology.term_name': {
'title': 'Biosample term name'
},
'file.assay_title': {
'title': 'Assay title'
},
'file.assembly': {
'title': 'Assembly'
},
'file.biosample_ontology.classification': {
'title': 'Biosample classification'
},
'file.biosample_ontology.organ_slims': {
'title': 'Biosample organ'
},
'dataset.replicates.library.biosample.sex': {
'title': 'Biosample sex'
},
'dataset.replicates.library.biosample.donor.organism.scientific_name': {
'title': 'Organism'
},
'dataset.biosample_summary': {
'title': 'Biosample summary'
},
'file.genome_annotation': {
'title': 'Genome annotation'
},
'file.donors': {
'title': 'Donors'
},
'file.@id': {
'title': 'File'
},
'dataset.@id': {
'title': 'Experiment'
}
},
'facets': {
'file.assay_title': {
'title': 'Assay title',
'open_on_load': True
},
'file.biosample_ontology.classification': {
'title': 'Biosample classification',
'open_on_load': True
},
'file.biosample_ontology.term_name': {
'title': 'Biosample term name',
'open_on_load': True,
'type': 'typeahead',
'length': 'long'
},
'file.assembly': {
'title': 'Assembly',
'open_on_load': True
},
'dataset.replicates.library.biosample.donor.organism.scientific_name': {
'title': 'Organism',
'open_on_load': True
},
'dataset.replicates.library.biosample.sex': {
'title': 'Biosample sex'
}
},
}
}
]
|
def square(x):
return x * x
def launch_missiles():
print('missiles launched')
def even_or_odd(n):
if n % 2 == 0:
print('even')
return
print('odd')
|
n = 1
for i in range(1, 10 + 1):
print(n)
n *= i
|
#!/usr/bin/env python
# coding: utf-8
# # Hill Cipher
# Below is the code to implement the Hill Cipher, which is an example of a **polyalphabetic cryptosystem**, that is, it does
# not assign a single ciphertext letter to a single plaintext letter, but rather a ciphertext letter may represent more than
# one plaintext letter. This example is from Judson's [Abstract Algebra](http://abstract.ups.edu/sage-aata.html) textbook,
# example 7.4. The encryption is based on the matrix
# \begin{equation*}
# A=\left(\begin{array}{cc}
# 3 & 5 \\
# 1 & 2
# \end{array}\right)
# \end{equation*}
# and encryptes pairs of letters at a time, rather than one letter at a time.
#
# The digitize and alphabetize functions are rather similar to the ones found in the CeasarCipher document, the bigest change
# being that these pair the numbers up so as to form matrices for encryption and decryption.
# In[ ]:
def digitize(string):
cipher_text = []
holder = []
for i in string:
if i == 'A' or i == 'a': holder.append(0)
if i == 'B' or i == 'b': holder.append(1)
if i == 'C' or i == 'c': holder.append(2)
if i == 'D' or i == 'd': holder.append(3)
if i == 'E' or i == 'e': holder.append(4)
if i == 'F' or i == 'f': holder.append(5)
if i == 'G' or i == 'g': holder.append(6)
if i == 'H' or i == 'h': holder.append(7)
if i == 'I' or i == 'i': holder.append(8)
if i == 'J' or i == 'j': holder.append(9)
if i == 'K' or i == 'k': holder.append(10)
if i == 'L' or i == 'l': holder.append(11)
if i == 'M' or i == 'm': holder.append(12)
if i == 'N' or i == 'n': holder.append(13)
if i == 'O' or i == 'o': holder.append(14)
if i == 'P' or i == 'p': holder.append(15)
if i == 'Q' or i == 'q': holder.append(16)
if i == 'R' or i == 'r': holder.append(17)
if i == 'S' or i == 's': holder.append(18)
if i == 'T' or i == 't': holder.append(19)
if i == 'U' or i == 'u': holder.append(20)
if i == 'V' or i == 'v': holder.append(21)
if i == 'W' or i == 'w': holder.append(22)
if i == 'X' or i == 'x': holder.append(23)
if i == 'Y' or i == 'y': holder.append(24)
if i == 'Z' or i == 'z': holder.append(25)
if len(holder)==2:
cipher_text.append(matrix(holder))
holder = []
if len(holder)==1:
holder.append(23)
cipher_text.append(matrix(holder))
return cipher_text
# In[ ]:
def alphabetize(digits):
plain_text = ""
comparison = MatrixSpace(IntegerModRing(26),1,1)
for number in digits:
for i in number:
if i == comparison([0])[0]: plain_text = plain_text + "A"
if i == comparison([1])[0]: plain_text = plain_text + "B"
if i == comparison([2])[0]: plain_text = plain_text + "C"
if i == comparison([3])[0]: plain_text = plain_text + "D"
if i == comparison([4])[0]: plain_text = plain_text + "E"
if i == comparison([5])[0]: plain_text = plain_text + "F"
if i == comparison([6])[0]: plain_text = plain_text + "G"
if i == comparison([7])[0]: plain_text = plain_text + "H"
if i == comparison([8])[0]: plain_text = plain_text + "I"
if i == comparison([9])[0]: plain_text = plain_text + "J"
if i == comparison([10])[0]: plain_text = plain_text + "K"
if i == comparison([11])[0]: plain_text = plain_text + "L"
if i == comparison([12])[0]: plain_text = plain_text + "M"
if i == comparison([13])[0]: plain_text = plain_text + "N"
if i == comparison([14])[0]: plain_text = plain_text + "O"
if i == comparison([15])[0]: plain_text = plain_text + "P"
if i == comparison([16])[0]: plain_text = plain_text + "Q"
if i == comparison([17])[0]: plain_text = plain_text + "R"
if i == comparison([18])[0]: plain_text = plain_text + "S"
if i == comparison([19])[0]: plain_text = plain_text + "T"
if i == comparison([20])[0]: plain_text = plain_text + "U"
if i == comparison([21])[0]: plain_text = plain_text + "V"
if i == comparison([22])[0]: plain_text = plain_text + "W"
if i == comparison([23])[0]: plain_text = plain_text + "X"
if i == comparison([24])[0]: plain_text = plain_text + "Y"
if i == comparison([25])[0]: plain_text = plain_text + "Z"
return plain_text
# Here we define the HillEncrypt and HillDecrypt functions, which take in strings, and encrypt or decrypt them according
# to the matrices passed into them as parameters.
# In[ ]:
def HillEncrypt(message, A, b):
encoded = digitize(message)
cipher_text = []
for item in encoded:
cipher_text.append(A*item.transpose()+b)
return alphabetize(cipher_text)
def HillDecrypt(message, A, b):
A = A.inverse()
encoded = digitize(message)
plain_text = []
for item in encoded:
plain_text.append(A*item.transpose()-A*b)
return alphabetize(plain_text)
# Here we use MatrixSpaces over the Ring of integers mod 26, to define the matrices used for encryption and decryption.
# We use MatrixSpaces rather than ordinary matrices to ensure that the inverse of $A$ is calculated correctly.
# In[ ]:
Z22_26 = MatrixSpace(IntegerModRing(26),2,2)
Z21_26 = MatrixSpace(IntegerModRing(26),2,1)
# these are the matrices used in the example in the book.
A = Z22_26([[3,5],[1,2]])
b = Z21_26([2,2])
# Here we go through our first example, which is the example in the book, encrypting the message "help".
# In[ ]:
message = "help"
encrypted = HillEncrypt(message,A,b)
print(encrypted)
decrypted = HillDecrypt(encrypted,A,b)
print(decrypted)
|
file = open('Advent-of-Code-2021\\Day 13\\Day 13 input.txt')
points = []
folds = []
for line in file:
line = line.strip()
if (line.find(',') != -1):
pointparse = line.split(',')
points.append([int(pointparse[0]),int(pointparse[1])])
elif (line.find('=') != -1):
foldparse = line.split('=')
folds.append([foldparse[0][len(foldparse[0])-1], int(foldparse[1])])
else:
"Do nothing"
for thisfold in folds:
newpoints = []
for point in points:
if (thisfold[0] == 'x'):
if (point[0] > thisfold[1]):
checkpoint = [thisfold[1]-(point[0]-thisfold[1]),point[1]]
if (checkpoint not in newpoints):
newpoints.append(checkpoint)
elif (point not in newpoints):
newpoints.append(point)
else:
"Do Nothing"
else:
if (point[1] > thisfold[1]):
checkpoint = [point[0],thisfold[1]-(point[1]-thisfold[1])]
if (checkpoint not in newpoints):
newpoints.append(checkpoint)
elif (point not in newpoints):
newpoints.append(point)
else:
"Do Nothing"
points = newpoints
maxX = 0
maxY = 0
for point in points:
if (point[0] > maxX):
maxX = point[0]
if (point[1] > maxY):
maxY = point[1]
outstring = []
for y in range(maxY+1):
row = ''
for x in range(maxX+1):
if ([x,y] in points):
row += '#'
else:
row += '.'
outstring.append(row)
for row in outstring:
print(row)
|
dummy1_iface_cfg = {
'INTERFACE': {
'MODULE': 'daq.interface.interface',
'CLASS': 'DummyInterface',
},
'IFCONFIG': {
'LABEL': 'Dummy1',
'ADDRESS': 'DummyAddress',
'SerialNumber': '1234',
}
}
dummycpc_inst_cfg = {
'INSTRUMENT': {
'MODULE': 'daq.instrument.instrument',
'CLASS': 'DummyInstrument',
},
'INSTCONFIG': {
'DESCRIPTION': {
'LABEL': 'DummyCPC',
'SERIAL_NUMBER': '0001',
'PROPERTY_NUMBER': 'CD0000001',
},
'IFACE_LIST': {
'DUMMY1': {
'IFACE_CONFIG': dummy1_iface_cfg,
'OPERATION': {
'POLLED': False,
'SAMPLE_FREQ_SEC': 1,
},
},
},
},
# could be IFACE_LIST to allow for multiple iface
}
dummy_controller_cfg = {
'CONTROLLER': {
'MODULE': 'daq.controller.controller',
'CLASS': 'Controller',
}
}
|
# @Title: 跳跃游戏 (Jump Game)
# @Author: 18015528893
# @Date: 2021-02-22 00:17:58
# @Runtime: 48 ms
# @Memory: 16 MB
class Solution:
def canJump(self, nums: List[int]) -> bool:
max_i = 0
last = len(nums) - 1
for i in range(len(nums)):
jump = nums[i]
if max_i >= i:
max_i = max(max_i, i+jump)
if max_i >= last:
return True
return False
|
# -*- coding: utf-8 -*-
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = float('inf')
# KeyInsigh: bit全探索
# 1つだけWAが取れなかった
# See:
# https://atcoder.jp/contests/s8pc-4/submissions/2122030
if n == 1:
print(0)
exit()
for bit in range(1 << (n - 1)):
color_count = 1
cost = 0
height_min = a[0]
for j in range(n - 1):
# 高さを変更しなくても、条件を満たしている
if height_min < a[j + 1]:
color_count += 1
height_min = a[j + 1]
continue
if bit & (1 << j):
cost += height_min - a[j + 1] + 1
color_count += 1
height_min += 1
if color_count >= k:
ans = min(ans, cost)
print(ans)
if __name__ == '__main__':
main()
|
print(dir(str))
nome = 'Flavio'
print(nome)
print(nome[:3])
texto = 'marca d\' agua'
print(texto)
texto = "marca d' agua"
print(texto)
texto = ''' texto
... texto
'''
print(texto)
texto = ' texto\n\t ...texto'
print(texto)
print(str.__add__('a', 'b'))
nome = 'Flavio Garcia Fernandes'
print(nome)
print(nome[-9:])
print(nome[::-1])
numeros = '0123456789'
print(numeros[1::2])
print(numeros[::2])
|
with open('in') as f:
data = list(map(lambda l: list(l.strip().replace(' ', '')), f.readlines()))
def evaluate(e):
value = None
operation = None
i = 0
while i < len(e):
c = e[i]
if c in '+*':
operation = c
elif c in '0123456789':
c = int(c)
if operation is None:
value = c
else:
if operation == '+':
value += c
else:
value *= c
elif c == '(':
tmp_e = []
i += 1
level = 1
while True:
if e[i] == '(':
level += 1
elif e[i] == ')':
level -= 1
if level == 0:
break
else:
tmp_e.append(e[i])
i += 1
b = evaluate(tmp_e)
if operation is None:
value = b
else:
if operation == '+':
value += b
else:
value *= b
else:
assert False
i += 1
return value
def evaluate_2(e):
i = 0
while i < len(e):
if e[i] == '+':
level = 0
index = -1
for j in range(i - 1, -1, -1):
if e[j] == ')':
level += 1
elif e[j] == '(':
level -= 1
if (level == 0 and e[j] in '+*') or (level < 0 and e[j] in '()'):
index = j
break
e.insert(index + 1, '(')
i += 1
level = 0
index = len(e)
for j in range(i + 1, len(e)):
if e[j] == '(':
level += 1
elif e[j] == ')':
level -= 1
if (level == 0 and e[j] in '+*') or (level < 0 and e[j] in '()'):
index = j
break
e.insert(index, ')')
i += 1
return evaluate(e)
def part_one():
return sum(map(evaluate, data))
def part_two():
return sum(map(evaluate_2, data))
if __name__ == '__main__':
print(f'Part One: {part_one()}')
print(f'Part Two: {part_two()}')
|
# just keep this as-is
def not_an_activity():
print("boom")
|
label_data = open("label", encoding='utf-8').readlines()
label_data = [x.strip() for x in label_data]
print(len(label_data))
label_kinds = set(label_data)
print(label_kinds)
|
class NotFoundError(Exception):
"""
Thrown during :meth:`get` when the requested object could not be found.
"""
pass
class ValidationError(Exception):
"""
Thrown by :class:`Field` subclasses when setting attributes that are
invalid.
"""
pass
|
def tupler(atuple):
print(f"{atuple=}")
return (1, 2, 3)
print(f"{type(tupler((10, 11)))=}")
|
# 代理模式
# 虚拟代理
class LazyProperty:
def __init__(self, method):
self.method = method
self.method_name = method.__name__
def __get__(self, instance, owner):
if not instance:
return None
value = self.method(instance)
setattr(instance, self.method_name, value)
return value
class Test:
def __init__(self):
self.x = 'foo'
self.y = 'bar'
self._resource = None
# resource方法使用LazyProperty修饰
@LazyProperty
def resource(self):
print(f'init resource: resource is {self._resource}')
self._resource = tuple(range(5))
return self._resource
# 保护代理
class NotFindError(Exception):
def __init__(self, msg):
self.msg = msg
class RealSubject:
def __init__(self):
self.score = {
"张三": 90,
"李四": 59,
"王二": 61
}
def num_students(self):
num = len(self.score.keys())
print("The number of students is {num}".format(num=num))
def get_score(self, user_name):
_score = self.score.get(user_name)
print("The score of {user} is {score}".format(user=user_name,
score=_score))
class Proxy(object):
def __init__(self):
self.default_passwd = "9l0skjlsa"
self.real_subject = RealSubject()
def num_students(self):
self.real_subject.num_students()
def get_score(self, user_name):
print("You are visiting {} score ...".format(user_name))
passwd = input("Please input password : ")
if passwd == self.default_passwd:
if user_name in self.real_subject.score.keys():
return self.real_subject.get_score(user_name)
else:
raise NotFindError("The student you are visiting not found.")
else:
raise ValueError("The password you provided is wrong!")
def client():
proxy = Proxy()
proxy.get_score("张三")
if __name__ == '__main__':
t = Test()
print(t.x)
print(t.y)
print(t.resource)
print(t.resource)
# 初始化字符串只执行了一次
client()
|
n1 = int (input())
s1 = set(map(int,input().split()))
n2 = int (input())
s2 = set(map(int,input().split()))
print(len(s1.intersection(s2)))
|
raio = int(input())
pi = 3.14159
volume = float(4.0 * pi * (raio* raio * raio) / 3)
print("VOLUME = %0.3f" %volume)
|
#!/usr/bin/env python
# encoding: utf-8
GRADES_FILENAME = 'grades.csv'
GRADING_SLASH_DELIMINATOR = '/'
SUBMISSIONS_FILENAME = 'Submissions'
GRADING_URL_EXTENSION = '&action=grading'
SUBMISSION_LISTING_DELIMINATOR = '-_submission_-'
GRADING_BLANK_GRADE = '-'
GRADING_HEADER_NAME = 'Name'
GRADING_HEADER_EMAIL = 'Email'
GRADING_HEADER_GRADE = 'Grade'
|
# display menu, list ciphers
class Menu:
def __init__(self, ciphers):
self.ciphers = ciphers
self.modes = ["encrypt", "decrypt"]
def get_mode(self):
print("Select one of the methods (enter number)")
for idx, mode in enumerate(self.modes):
print("{0}: {1}".format(idx, mode))
self.mode = int(input("Enter a number please: "))
self.mode = self.modes[self.mode]
def get_cipher(self):
print("Select a cipher please (enter number)")
for idx, encryption in enumerate(self.ciphers):
print("{0}: {1}".format(idx, encryption))
self.cipher = int(input("Enter a number please: "))
self.cipher = self.ciphers[self.cipher]
def get_key(self): # if homophonic: popup file explorer for key file selection
if self.cipher != "homophonic substitution":
self.key = input("Enter your key please: ")
def get_msg(self):
# legg til mulighet for å velge en fil
self.msg = input("Enter your message please: ")
def main(self):
self.get_mode()
self.get_cipher()
self.get_key()
self.get_msg()
print("\nMenu done.")
if __name__ == "__main__":
menu = Menu(["ceasar", "binary", "foo"])
menu.main()
|
#print("for loop")
#word = ["this", "is","roshan"]
# for w in word: print(w, len(w))
#give range of each word for w in range(len(word)): print(w, word[w])
#get odd or even
"""
for x in range(0,5):
x+=1
#print(x)
if x % 2 == 0:
print(f"{x}::Even No")
else:
print(f"{x}::Odd No")
print("PRime No's")
for n in range(1,10):
for x in range(2,n):
if n % x ==0:
print(f"{n} get by multiple of {x} and is divisible of {x}, So it is not a prime no")
break
else:
print(f"{n} is prime no")
"""
#Loop while for the printing numbers
def whileloop(x):
y=0
while(y<x):
print(y)
y=y+1
#print number using for loop
def forloop(x):
y=0
for i in range(y,x):
print(i)
#print even or odd based on the condition
def printodd(x):
y=0
for i in range(y,x):
if(i%2 != 0): continue
print("Even No: ",i)
for i in range(y,x):
if(i%2 == 0): continue
print("Odd No: ",i)
printodd(10)
#whileloop(10)
#forloop(10)
|
# Time: O(n)
# Space: O(n)
class UnionFind(object):
def __init__(self, n):
self.set = range(n)
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x]
def union_set(self, x, y):
x_root, y_root = map(self.find_set, (x, y))
if x_root == y_root:
return False
self.set[min(x_root, y_root)] = max(x_root, y_root)
return True
class Solution(object):
def removeStones(self, stones):
"""
:type stones: List[List[int]]
:rtype: int
"""
MAX_ROW = 10000
union_find = UnionFind(2*MAX_ROW)
for r, c in stones:
union_find.union_set(r, c+MAX_ROW)
return len(stones) - len({union_find.find_set(r) for r, _ in stones})
|
# IP and port to bind to.
bind = ['127.0.0.1:4000']
# Maximum number of pending connections.
backlog = 2048
# Number of worker processes to handle connections.
workers = 2
# Fork main process to background.
daemon = True
# PID file to write to.
pidfile = "web.gunicorn.pid"
# Allow connections from any frontend proxy.
# forwarded_allow_ips = '*'
# Logging configuration.
accesslog = "web.gunicorn.access.log"
errorlog = "web.gunicorn.error.log"
loglevel = "warning"
# Gunicorn process name.
proc_name = "rouly.net-gunicorn"
|
# Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente.
print('-' * 100)
print('{: ^100}'.format('EXERCÍCIO 027 - PRIMEIRO E ÚLTIMO NOME DE UMA PESSOA'))
print('-' * 100)
nome = str(input('Digite seu nome completo: ')).title().strip().split()
print(f'Primeiro nome: {nome[0]}')
print(f'Último nome: {nome[-1]}')
print('-' * 100)
input('Pressione ENTER para sair...')
|
lista = [[],[]]
for i in range(7):
num = int(input(f'Digite o {i+1}o. valor: '))
if num%2 == 0:
lista[0].append(num)
else:
lista[1].append(num)
print(f'Os valores pares digitados foram: {sorted(lista[0])}')
print(f'Os valores ímpares digitados foram: {sorted(lista[1])}')
|
i = 0
while(True):
if i+1<5:
i = i + 1
continue
print(i+1, end=" ")
if(i==50):
break #stop the loop
i = i+ 1
|
#https://leetcode.com/problems/min-stack/
class MinStack(object):
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append((x, min(x, self.getMin())))
def pop(self):
if len(self.stack)==0: return None
return self.stack.pop()[0]
def top(self):
if len(self.stack)==0: return None
return self.stack[-1][0]
def getMin(self):
if len(self.stack)==0: return float('inf')
return self.stack[-1][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
# -*- coding: utf-8 -*-
"""
flybirds common error
"""
class FlybirdNotFoundException(Exception):
"""
not find flybirds
"""
def __init__(self, message, select_dic, error=None):
message = f"selectors={str(select_dic)} {message}"
if error is not None:
message = f"{message} innerErr:{error}"
super().__init__(message)
self.message = message
def __str__(self):
return str(self.message)
class PositionNotChangeException(Exception):
"""
position not change
"""
def __init__(self, message):
super().__init__(message)
self.message = message
def __str__(self):
return str(self.message)
class FlybirdCallMethodParamsException(Exception):
"""
params error
"""
def __init__(self, method, param_name):
message = f"call method:{method} has invalid params:{param_name}"
super().__init__(message)
self.message = message
def __str__(self):
return str(self.message)
class FlybirdEleExistsException(Exception):
"""
ele not exists
"""
def __init__(self, message):
super().__init__(message)
self.message = message
def __str__(self):
return str(self.message)
class FlybirdVerifyException(Exception):
"""
verify error
"""
def __init__(self, message):
super().__init__()
self.message = message
def __str__(self):
return str(self.message)
class FlybirdPositionChanging(Exception):
"""
position changing
"""
def __init__(self, message):
super().__init__()
self.message = message
def __str__(self):
return str(self.message)
class ScreenRecordException(Exception):
"""
screen record error
"""
def __init__(self, message):
super().__init__()
self.message = message
def __str__(self):
return str(self.message)
|
class RaggedContiguous:
"""Mixin class for an underlying compressed ragged array.
.. versionadded:: (cfdm) 1.7.0
"""
def get_count(self, default=ValueError()):
"""Return the count variable for a compressed array.
.. versionadded:: (cfdm) 1.7.0
:Parameters:
default: optional
Return the value of the *default* parameter if the
count variable has not been set.
{{default Exception}}
:Returns:
The count variable.
**Examples:**
>>> c = d.get_count()
"""
out = self._get_component("count_variable", None)
if out is None:
return self._default(
default, f"{self.__class__.__name__!r} has no count variable"
)
return out
|
## This module deals with code regarding handling the double
## underscore separated keys
def dunderkey(*args):
"""Produces a nested key from multiple args separated by double
underscore
>>> dunderkey('a', 'b', 'c')
>>> 'a__b__c'
:param *args : *String
:rtype : String
"""
return '__'.join(args)
def dunder_partition(key):
"""Splits a dunderkey into 2 parts
The first part is everything before the final double underscore
The second part is after the final double underscore
>>> dunder_partition('a__b__c')
>>> ('a__b', 'c')
:param neskey : String
:rtype : 2 Tuple
"""
parts = key.rsplit('__', 1)
return tuple(parts) if len(parts) > 1 else (parts[0], None)
def dunder_init(key):
"""Returns the initial part of the dunder key
>>> dunder_init('a__b__c')
>>> 'a__b'
:param neskey : String
:rtype : String
"""
return dunder_partition(key)[0]
def dunder_last(key):
"""Returns the last part of the dunder key
>>> dunder_last('a__b__c')
>>> 'c'
:param neskey : String
:rtype : String
"""
return dunder_partition(key)[1]
def dunder_get(_dict, key):
"""Returns value for a specified dunderkey
A "dunderkey" is just a fieldname that may or may not contain
double underscores (dunderscores!) for referrencing nested keys in
a dict. eg::
>>> data = {'a': {'b': 1}}
>>> nesget(data, 'a__b')
1
key 'b' can be referrenced as 'a__b'
:param _dict : (dict)
:param key : (str) that represents a first level or nested key in the dict
:rtype : (mixed) value corresponding to the key
"""
parts = key.split('__', 1)
key = parts[0]
try:
result = _dict[key]
except KeyError:
return None
except TypeError:
try:
result = getattr(_dict, key)
except AttributeError:
return None
return result if len(parts) == 1 else dunder_get(result, parts[1])
def undunder_keys(_dict):
"""Returns dict with the dunder keys converted back to nested dicts
eg::
>>> undunder_keys({'a': 'hello', 'b__c': 'world'})
{'a': 'hello', 'b': {'c': 'world'}}
:param _dict : (dict) flat dict
:rtype : (dict) nested dict
"""
def f(key, value):
parts = key.split('__')
return {
parts[0]: value if len(parts) == 1 else f(parts[1], value)
}
result = {}
for r in [f(k, v) for k, v in _dict.items()]:
rk = list(r.keys())[0]
if rk not in result:
result.update(r)
else:
result[rk].update(r[rk])
return result
def dunder_truncate(_dict):
"""Returns dict with dunder keys truncated to only the last part
In other words, replaces the dunder keys with just last part of
it. In case many identical last parts are encountered, they are
not truncated further
eg::
>>> dunder_truncate({'a__p': 3, 'b__c': 'no'})
{'c': 'no', 'p': 3}
>>> dunder_truncate({'a__p': 'yay', 'b__p': 'no', 'c__z': 'dunno'})
{'a__p': 'yay', 'b__p': 'no', 'z': 'dunno'}
:param _dict : (dict) to flatten
:rtype : (dict) flattened result
"""
keylist = list(_dict.keys())
def decide_key(k, klist):
newkey = dunder_last(k)
return newkey if list(map(dunder_last, klist)).count(newkey) == 1 else k
original_keys = [decide_key(key, keylist) for key in keylist]
return dict(zip(original_keys, _dict.values()))
|
def insert_newlines(string, every=64):
return '\n'.join(string[i:i+every] for i in range(0, len(string), every))
for __ in range(int(input())):
n = int(input())
o = "O"
x = "X"
a = ["X" for i in range(64)]
for i in range(n):
a[i] = "."
a[0]=o
print(insert_newlines("".join(a),8))
|
## Set Configs
print('Set configs..')
sns.set()
pd.options.display.max_columns = None
RANDOM_SEED = 42
fig_path = os.path.join(os.getcwd(), 'figs')
model_path = os.path.join(os.getcwd(), 'models')
model_bib_path = os.path.join(model_path,'model_bib')
data_path = os.path.join(os.getcwd(), 'data')
## read the data
print('Read the data..')
data_fn = os.path.join(data_path, 'simulation_data_y_2020_2021_reduced.h5')
df_data = pd.read_hdf(data_fn, key='df')
print('Shape of normal data (X_sim): {}'.format(df_data.shape))
data_fn_anormal = os.path.join(data_path, 'anomalous_data_y_2022_reduced.h5')
df_data_anormal = pd.read_hdf(data_fn_anormal, key='df')
print('Shape of anormal data (X_test): {}'.format(df_data_anormal.shape))
data_fn_drifted = os.path.join(data_path, 'drifted_data_y_2023_reduced_more_cos_phi.h5')
df_data_drifted = pd.read_hdf(data_fn_drifted, key='df')
print('Shape of drifted data (X_drifted): {}'.format(df_data_drifted.shape))
data_fn_drifted_anormal = os.path.join(data_path, 'anomalous_drifted_data_y_2023_reduced_more_cos_phi.h5')
df_data_drifted_anormal = pd.read_hdf(data_fn_drifted_anormal, key='df')
print('Shape of drifted anormal data (X_drifted,anormal): {}'.format(df_data_drifted_anormal.shape))
## save label
print('Save label..')
s_labels = df_data_anormal['label']
df_data_anormal.drop('label', axis=1, inplace=True)
print('Shape of anormal data (X_test): {}'.format(df_data_anormal.shape))
s_drift_labels = df_data_drifted['drift_labels']
df_data_drifted.drop('drift_labels',axis=1,inplace=True)
print('Shape of drifted data (X_drifted): {}'.format(df_data_drifted.shape))
s_drift_labels_drifted_ano = df_data_drifted_anormal['drift_labels']
df_data_drifted_anormal.drop('drift_labels', axis=1, inplace=True)
s_ano_labels_drifted_ano = df_data_drifted_anormal['anomaly_labels']
df_data_drifted_anormal.drop('anomaly_labels', axis=1, inplace=True)
print('Shape of drifted anormal data (X_drifted,anormal): {}'.format(df_data_drifted_anormal.shape))
### Scale data
print('Scale data..')
scaler_train = MinMaxScaler((-1,1))
scaler_train = scaler_train.fit(df_data)
scaled_anormal = scaler_train.transform(df_data_anormal.to_numpy())
scaled_normal = scaler_train.transform(df_data.to_numpy())
scaled_drifted = scaler_train.transform(df_data_drifted.to_numpy())
scaled_drifted_anormal = scaler_train.transform(df_data_drifted_anormal.to_numpy())
## prepare for PyTorch
print('Prepare data for PyTorch..')
# build tensor from numpy
anormal_torch_tensor = torch.from_numpy(scaled_anormal).type(torch.FloatTensor)
normal_torch_tensor = torch.from_numpy(scaled_normal).type(torch.FloatTensor)
drifted_torch_tensor = torch.from_numpy(scaled_drifted).type(torch.FloatTensor)
drifted_anormal_torch_tensor = torch.from_numpy(scaled_drifted_anormal).type(torch.FloatTensor)
# build TensorDataset from Tensor
anormal_dataset = TensorDataset(anormal_torch_tensor, anormal_torch_tensor)
normal_dataset = TensorDataset(normal_torch_tensor, normal_torch_tensor)
drifted_dataset = TensorDataset(drifted_torch_tensor, drifted_torch_tensor)
drifted_anormal_dataset = TensorDataset(drifted_anormal_torch_tensor, drifted_anormal_torch_tensor)
# build DataLoader from TensorDataset
anormal_dataloader = torch.utils.data.DataLoader(anormal_dataset,batch_size=128,shuffle=False, num_workers=0)
normal_dataloader = torch.utils.data.DataLoader(normal_dataset,batch_size=128,shuffle=False, num_workers=0)
drifted_dataloader = torch.utils.data.DataLoader(drifted_dataset,batch_size=128,shuffle=False, num_workers=0)
drifted_anormal_dataloader = torch.utils.data.DataLoader(drifted_anormal_dataset, batch_size=128, shuffle=False, num_workers=0)
|
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# dumb way
# for i in range(0,len(a),1):
# if a[i]%2 == 0:
# print(str(a[i]),end=" ")
b = [i for i in a if i % 2 == 0]
print(b)
|
'''
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
'''
class Solution:
def romanToInt(self, s: str) -> int:
roman = {'I' : 1,
'V' : 5,
'X' : 10,
'L' : 50,
'C' : 100,
'D' : 500,
'M' : 1000 }
ans = 0
for i in range(len(s)):
if i < len(s) - 1 and roman[s[i]] < roman[s[i + 1]]:
ans -= roman[s[i]]
else:
ans += roman[s[i]]
return ans
|
# https://www.codewars.com/kata/55a243393fb3e87021000198/train/python
# My solution
def remember(text):
counter = {}
result = []
for ch in text:
counter[ch] = counter.get(ch, 0) + 1
if counter[ch] == 2:
result.append(ch)
return result
# ...
def remember(str_):
seen = set()
res = []
for i in str_:
res.append(i) if i in seen and i not in res else seen.add(i)
return res
|
directory_map = {
"abilene": "directed-abilene-zhang-5min-over-6months-ALL",
"geant": "directed-geant-uhlig-15min-over-4months-ALL",
"germany50": "directed-germany50-DFN-aggregated-1day-over-1month",
}
|
class Math1():
def __init__(self):
self.my_num1 = 10
self.my_num2 = 20
def addition(self):
return self.my_num1 + self.my_num2
def subtraction(self):
return self.my_num1 - self.my_num2
class Math_Plus(Math1):
def __init__(self, my_num1=40, my_num2=90):
self.my_num1 = my_num1
self.my_num2 = my_num2
def multiplication(self):
return self.my_num1 * self.my_num2
def division(self):
return self.my_num1 / self.my_num2
if __name__ == "__main__":
math1 = Math1()
print(math1.addition()) #30
print(math1.subtraction()) #-10
math_plus = Math_Plus()
print(math_plus.addition()) #130
print(math_plus.subtraction()) #-50
print(math_plus.multiplication()) #3600
print(math_plus.division()) #0.-44444444
|
# single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "0.6.0"
# app name to send as part of SDK requests
app_name = "DLHub CLI v{}".format(__version__)
|
# coding: utf8
# try something like
def index(): return plugin_flatpage()
def rfp(): return plugin_flatpage()
|
# Exercício Python 69: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: A) quantas pessoas tem mais de 18 anos. B) quantos homens foram cadastrados. C) quantas mulheres tem menos de 20 anos.
i = m = f = 0
while True:
idade = int(input("Idade: "))
if idade >= 18:
i += 1
sexo = " "
while sexo not in "MmFf":
sexo = input("Sexo: [M/F] ").strip()[0]
if sexo in "Mm":
m += 1
elif sexo in "Ff" and idade < 20:
f += 1
continua = " "
while continua not in "SsNn":
continua = input("Deseja continuar? [S/N] ").strip()[0]
if continua in "Nn":
break
print(f"Foram cadastrados {i} pessoas com mais de 18, {m} homens e {f} mulheres com menos de 20 anos.")
|
"""
MicroPython driver for MLX90615 IR temperature I2C sensor :
https://github.com/rcolistete/MicroPython_MLX90615_driver
Version with simple read functions : 0.2.1 @ 2020/05/05
Author: Roberto Colistete Jr. (roberto.colistete at gmail.com)
License: MIT License (https://opensource.org/licenses/MIT)
"""
__version__ = '0.2.1'
MLX90615_I2C_DEFAULT_ADDR = const(0x5B)
_REG_ID_LOW = const(0x1E) # EEPROM register - ID number low
_REG_ID_HIGH = const(0x1F) # EEPROM register - ID number high
_REG_AMBIENT_TEMP = const(0x26) # RAM register - ambient temperature register
_REG_OBJECT_TEMP = const(0x27) # RAM register - object temperature register
class MLX90615:
def __init__(self, i2c, address=MLX90615_I2C_DEFAULT_ADDR):
self.i2c = i2c
self.address = address
self.buf = bytearray(3)
def _crc8(self, icrc, data):
crc = icrc ^ data
for _ in range(8):
crc <<= 1
if crc & 0x0100:
crc ^= 0x07
crc &= 0xFF
return crc
def read16(self, register, crc_check=True):
self.i2c.readfrom_mem_into(self.address, register, self.buf)
lsb = self.buf[0]
msb = self.buf[1]
pec = self.buf[2]
crc = 0
if crc_check:
crc = self._crc8(crc, self.address << 1)
crc = self._crc8(crc, register)
crc = self._crc8(crc, (self.address << 1) + 1)
crc = self._crc8(crc, lsb)
crc = self._crc8(crc, msb)
if (not crc_check) or (pec == crc):
return lsb | (msb << 8)
else:
raise Exception("PEC != CRC8 error in reading register {:02x}.".format(register))
def read_ambient_temp(self, pec_check=True):
try:
t = self.read16(_REG_AMBIENT_TEMP, crc_check=pec_check)
except Exception as err:
raise Exception("Error reading ambient temperature.\n{}".format(err))
else:
if (t > 0x7FFF):
raise Exception("Invalid ambient temperature error.")
else:
return t*2 - 27315
def read_object_temp(self, pec_check=True):
try:
t = self.read16(_REG_OBJECT_TEMP, crc_check=pec_check)
except Exception as err:
raise Exception("Error reading object temperature.\n{}".format(err))
else:
if (t > 0x7FFF):
raise Exception("Invalid object temperature error.")
else:
return t*2 - 27315
def read_id(self, pec_check=True):
try:
return self.read16(_REG_ID_LOW, crc_check=pec_check) | (self.read16(_REG_ID_HIGH, crc_check=pec_check) << 16)
except Exception as err:
raise Exception("Error reading sensor ID.\n{}".format(err))
def read_eeprom(self, pec_check=True):
eeprom_data = [0]*0x10
for register in range(0x10, 0x20):
try:
eeprom_data[register - 0x10] = self.read16(register, crc_check=pec_check)
except Exception as err:
raise Exception("Error reading EEPROM.\n{}".format(err))
return eeprom_data
|
# -*- coding: utf-8 -*-
"""Contains version information"""
__version__ = "0.7.9"
|
'''
PyTorch implementation of the RetinaNet object detector:
Lin, Tsung-Yi, et al. "Focal loss for dense object detection." Proceedings of the IEEE international conference on computer vision. 2017.
Basic implementation forked and adapted from: https://github.com/kuangliu/pytorch-retinanet
2019 Benjamin Kellenberger
'''
# default options for the model, may be overridden in the custom configuration loaded at runtime
DEFAULT_OPTIONS = {
"general": {
"image_size": [800, 600],
"device": "cuda",
"seed": 1234
},
"model": {
"kwargs": {
"backbone": "resnet50",
"pretrained": False,
"out_planes": 256,
"convertToInstanceNorm": False
}
},
"train": {
"dataLoader": {
"kwargs": {
"shuffle": True,
"batch_size": 32
}
},
"optim": {
"class": "torch.optim.Adam",
"kwargs": {
"lr": 1e-7,
"weight_decay": 0.0
}
},
"transform": {
"class": "ai.models.pytorch.boundingBoxes.Compose",
"kwargs": {
"transforms": [{
"class": "ai.models.pytorch.boundingBoxes.Resize",
"kwargs": {
"size": [800, 600]
}
},
{
"class": "ai.models.pytorch.boundingBoxes.RandomHorizontalFlip",
"kwargs": {
"p": 0.5
}
},
{
"class": "ai.models.pytorch.boundingBoxes.DefaultTransform",
"kwargs": {
"transform": {
"class": "torchvision.transforms.ColorJitter",
"kwargs": {
"brightness": 0.25,
"contrast": 0.25,
"saturation": 0.25,
"hue": 0.01
}
}
}
},
{
"class": "ai.models.pytorch.boundingBoxes.DefaultTransform",
"kwargs": {
"transform": {
"class": "torchvision.transforms.ToTensor"
}
}
},
{
"class": "ai.models.pytorch.boundingBoxes.DefaultTransform",
"kwargs": {
"transform": {
"class": "torchvision.transforms.Normalize",
"kwargs": {
"mean": [0.485, 0.456, 0.406],
"std": [0.229, 0.224, 0.225]
}
}
}
}
]
}
},
"criterion": {
"class": "ai.models.pytorch.functional._retinanet.loss.FocalLoss",
"kwargs": {
"gamma": 2.0,
"alpha": 0.25,
"background_weight": 1.0
}
},
"ignore_unsure": True
},
"inference": {
"transform": {
"class": "ai.models.pytorch.boundingBoxes.Compose",
"kwargs": {
"transforms": [{
"class": "ai.models.pytorch.boundingBoxes.Resize",
"kwargs": {
"size": [800, 600]
}
},
{
"class": "ai.models.pytorch.boundingBoxes.DefaultTransform",
"kwargs": {
"transform": {
"class": "torchvision.transforms.ToTensor"
}
}
},
{
"class": "ai.models.pytorch.boundingBoxes.DefaultTransform",
"kwargs": {
"transform": {
"class": "torchvision.transforms.Normalize",
"kwargs": {
"mean": [0.485, 0.456, 0.406],
"std": [0.229, 0.224, 0.225]
}
}
}
}
]
}
},
"dataLoader": {
"kwargs": {
"shuffle": False,
"batch_size": 32
}
}
}
}
|
#Faça um programa que leia três números inteiros e colocá-los em ordem crescente.
#Sugestão: Sejam 3 números A, B e C. A ideia principal é:
# – armazenar em A o menor valor
# – armazenar em B o valor intermediário
# – armazenar em C o maior valor
a = int(input("Digite um número para a: "))
b = int(input("Digite um número para b: "))
c = int(input("Digite um número para c: "))
#a é o menor:
if a < b and a < c:
if b < c:
print("{}, {}, {}".format(a, b, c))
else:
print("{},{},{}".format(a, c, b))
#b é menor:
elif b < a and b < c:
if a < c:
print("{}, {}, {}".format(b, a, c))
else:
print("{}, {}, {}".format(b, c, a))
else:
if a > b:
print("{}, {}, {}".format(c, b, a))
else:
print("{}, {}, {}".format(c, a, b))
|
#import gui.gui as gui
# Python3 program to find number
# of bins required using
# First Fit algorithm.
# Returns number of bins required
# using first fit
# online algorithm
def firstFit(weight, n, c):
# Initialize result (Count of bins)
res = 0
# Create an array to store
# remaining space in bins
# there can be at most n bins
bin_rem = [0]*n
# Place items one by one
for i in range(n):
# Find the first bin that
# can accommodate
# weight[i]
j = 0
# Initialize minimum space
# left and index
# of best bin
min = c + 1
bi = 0
for j in range(res):
if (bin_rem[j] >= weight[i] and bin_rem[j] -
weight[i] < min):
bi = j
min = bin_rem[j] - weight[i]
# If no bin could accommodate weight[i],
# create a new bin
if (min == c + 1):
bin_rem[res] = c - weight[i]
res += 1
else: # Assign the item to best bin
bin_rem[bi] -= weight[i]
return res
# Driver code
if __name__ == '__main__':
weight = [ 10, 5, 10, 7, 1, 10, 10 ]
c = 10
n = len(weight)
print("Number of bins required in First Fit : ",
firstFit(weight, n, c))
|
# mapping for AWS IAM user_name to slack ID accross all AWS accounts
#
# Fill in "<aws_IAM_user_id>:<slack_id>" here. Seperate each entry by a comma, and leave the last one without a comma
# Example:
# mapping = {
# "IAM_user_id1":"slack_id1",
# "IAM_user_id2":"slack_id2",
# "IAM_user_id3":"slack_id3"
# }
mapping = {
"IAM_user_id1":"slack_id1",
"IAM_user_id2":"slack_id2",
"IAM_user_id3":"slack_id3"
}
|
vents = """964,133 -> 596,133
920,215 -> 920,976
123,528 -> 123,661
613,13 -> 407,13
373,876 -> 424,876
616,326 -> 120,326
486,335 -> 539,388
104,947 -> 54,947
319,241 -> 282,204
453,175 -> 453,438
485,187 -> 915,617
863,605 -> 603,605
870,524 -> 342,524
967,395 -> 634,62
405,181 -> 807,181
961,363 -> 419,905
89,586 -> 214,461
545,481 -> 731,295
407,678 -> 626,678
421,642 -> 91,312
11,22 -> 935,946
770,208 -> 76,902
668,858 -> 668,890
568,451 -> 574,451
233,56 -> 371,56
233,932 -> 44,932
404,81 -> 796,81
520,77 -> 403,194
296,736 -> 447,887
210,909 -> 16,909
692,483 -> 877,668
777,289 -> 744,289
22,760 -> 652,130
96,360 -> 626,360
101,267 -> 101,783
47,667 -> 660,667
805,682 -> 563,440
112,15 -> 463,366
406,808 -> 430,808
793,767 -> 107,81
560,534 -> 958,534
722,429 -> 722,459
646,889 -> 646,195
433,942 -> 449,958
716,503 -> 716,99
266,450 -> 266,780
316,81 -> 565,81
760,452 -> 687,452
976,983 -> 15,22
499,564 -> 499,909
839,913 -> 38,112
707,333 -> 438,333
47,644 -> 352,644
807,309 -> 807,706
434,686 -> 812,308
559,572 -> 63,76
493,352 -> 581,352
94,88 -> 928,88
898,738 -> 106,738
201,10 -> 564,10
976,914 -> 976,472
836,153 -> 585,153
178,43 -> 17,204
784,967 -> 738,967
370,359 -> 449,359
13,526 -> 637,526
399,158 -> 10,158
572,293 -> 289,293
627,674 -> 895,674
921,402 -> 984,402
907,667 -> 944,704
574,877 -> 882,569
977,977 -> 121,121
550,584 -> 862,584
396,556 -> 396,289
391,33 -> 532,174
12,988 -> 989,11
48,787 -> 48,637
476,638 -> 113,638
985,985 -> 13,13
838,784 -> 198,784
567,195 -> 677,305
174,251 -> 577,654
296,801 -> 53,558
983,899 -> 983,380
507,230 -> 507,929
264,516 -> 668,920
865,952 -> 865,768
522,290 -> 744,512
936,958 -> 936,115
527,871 -> 527,519
944,972 -> 21,49
880,380 -> 695,565
471,374 -> 446,349
503,597 -> 127,221
471,514 -> 30,73
890,232 -> 890,511
14,461 -> 14,853
167,676 -> 148,676
987,230 -> 754,230
797,725 -> 797,847
347,21 -> 84,21
839,274 -> 964,274
607,456 -> 894,456
335,949 -> 301,949
167,236 -> 820,889
87,558 -> 87,917
318,788 -> 622,484
699,583 -> 699,321
971,967 -> 35,31
420,44 -> 420,36
29,484 -> 458,484
768,157 -> 768,30
690,839 -> 317,839
870,578 -> 560,578
697,195 -> 70,822
689,45 -> 689,223
790,724 -> 341,724
694,291 -> 694,507
43,339 -> 43,987
590,733 -> 590,179
751,361 -> 945,361
99,820 -> 450,469
460,696 -> 942,696
783,940 -> 487,644
630,537 -> 48,537
643,856 -> 643,396
558,733 -> 257,432
16,972 -> 570,418
636,188 -> 636,610
868,138 -> 868,407
85,424 -> 85,919
710,932 -> 354,576
356,505 -> 783,505
606,876 -> 606,62
577,431 -> 749,431
108,262 -> 108,145
615,455 -> 264,104
205,754 -> 866,754
189,182 -> 855,848
10,43 -> 925,958
293,773 -> 293,534
746,313 -> 802,369
607,174 -> 211,570
860,840 -> 260,240
879,78 -> 595,78
11,143 -> 449,143
190,983 -> 267,983
912,92 -> 76,928
744,364 -> 744,258
436,417 -> 46,807
629,592 -> 517,592
113,893 -> 113,959
714,213 -> 786,285
868,165 -> 868,731
349,69 -> 491,69
278,430 -> 111,263
593,849 -> 593,203
156,860 -> 876,860
169,615 -> 169,984
983,93 -> 139,937
94,548 -> 18,548
623,72 -> 106,589
530,334 -> 473,334
384,746 -> 925,205
711,74 -> 28,757
850,728 -> 629,949
378,801 -> 228,651
347,968 -> 201,822
82,578 -> 82,555
149,405 -> 707,963
254,169 -> 793,169
443,454 -> 331,454
460,659 -> 608,807
838,807 -> 31,807
561,952 -> 290,952
755,626 -> 204,75
550,424 -> 550,81
772,115 -> 772,600
40,517 -> 40,232
277,841 -> 317,841
899,150 -> 128,921
735,332 -> 465,332
839,254 -> 915,330
959,616 -> 182,616
729,723 -> 487,965
64,838 -> 953,838
689,830 -> 689,982
191,83 -> 191,879
522,833 -> 942,833
877,785 -> 877,346
255,95 -> 556,95
782,491 -> 475,798
268,815 -> 812,271
119,181 -> 905,181
445,457 -> 742,160
973,30 -> 27,976
356,681 -> 356,289
882,279 -> 914,279
672,162 -> 672,153
180,729 -> 357,729
985,716 -> 985,313
191,618 -> 191,963
949,749 -> 636,749
289,902 -> 142,902
923,615 -> 123,615
710,929 -> 541,760
211,402 -> 211,433
515,178 -> 533,178
525,869 -> 525,578
201,569 -> 17,569
629,848 -> 882,848
152,512 -> 152,189
914,723 -> 764,723
218,231 -> 721,734
438,382 -> 846,382
582,475 -> 582,559
529,943 -> 529,683
330,312 -> 59,312
242,900 -> 862,900
271,220 -> 271,118
182,459 -> 182,673
513,265 -> 513,420
918,942 -> 378,942
277,765 -> 812,230
625,874 -> 219,874
737,533 -> 644,626
647,975 -> 152,480
638,284 -> 785,284
549,680 -> 549,877
886,278 -> 372,792
130,560 -> 516,174
186,741 -> 186,555
208,536 -> 469,536
674,906 -> 312,906
934,156 -> 934,322
568,412 -> 214,412
243,19 -> 243,814
861,230 -> 104,987
683,891 -> 683,533
545,740 -> 545,980
343,320 -> 796,320
821,220 -> 821,302
578,741 -> 578,141
633,405 -> 27,405
645,975 -> 225,555
25,527 -> 412,527
378,817 -> 378,913
352,741 -> 352,293
48,986 -> 925,109
506,231 -> 491,231
854,883 -> 48,77
261,221 -> 895,855
902,240 -> 902,943
145,338 -> 770,963
832,216 -> 832,869
480,385 -> 324,385
644,202 -> 433,202
202,176 -> 190,176
668,693 -> 668,349
95,230 -> 143,230
873,144 -> 67,950
232,509 -> 238,509
963,43 -> 133,873
527,631 -> 641,517
363,61 -> 849,61
72,326 -> 72,861
542,801 -> 233,492
247,48 -> 247,785
972,563 -> 480,71
362,870 -> 932,300
263,811 -> 263,584
556,157 -> 417,157
946,900 -> 175,129
790,542 -> 530,542
777,195 -> 154,818
71,764 -> 71,193
197,13 -> 453,13
664,714 -> 158,714
257,819 -> 257,730
796,927 -> 688,927
124,53 -> 954,883
30,16 -> 980,966
84,151 -> 597,151
840,776 -> 684,776
548,460 -> 718,630
291,635 -> 291,151
948,43 -> 58,933
373,483 -> 373,591
309,81 -> 259,81
692,808 -> 692,835
737,112 -> 215,634
808,595 -> 808,115
160,912 -> 973,99
494,191 -> 494,475
713,925 -> 43,255
736,580 -> 290,134
257,679 -> 725,211
464,81 -> 712,81
35,147 -> 35,420
372,159 -> 372,548
508,228 -> 682,402
120,491 -> 518,889
139,948 -> 272,815
398,523 -> 398,818
935,50 -> 40,945
415,959 -> 195,739
250,868 -> 250,930
77,60 -> 917,900
584,389 -> 493,298
362,163 -> 362,704
670,740 -> 670,703
689,297 -> 689,388
988,572 -> 988,340
238,248 -> 238,916
748,753 -> 29,34
184,565 -> 184,486
812,217 -> 812,34
60,140 -> 96,104
826,673 -> 230,673
221,221 -> 207,235
449,483 -> 270,304
805,810 -> 805,564
952,52 -> 139,865
428,967 -> 312,851
854,673 -> 661,673
985,209 -> 853,209
523,365 -> 54,365
492,171 -> 646,171
908,853 -> 69,14
38,698 -> 724,12
400,479 -> 167,479
948,313 -> 948,976
280,145 -> 37,145
206,858 -> 683,381
203,413 -> 545,413
726,173 -> 673,173
30,954 -> 150,954
319,592 -> 870,41
808,91 -> 180,719
845,612 -> 972,485
160,430 -> 160,780
19,339 -> 379,339
476,550 -> 476,291
341,785 -> 229,673
371,476 -> 371,663
509,836 -> 412,933
980,20 -> 31,969
822,526 -> 328,32
859,314 -> 425,314
963,961 -> 963,100
984,978 -> 31,25
659,251 -> 619,211
649,477 -> 846,477
32,259 -> 724,951
468,753 -> 468,91
690,301 -> 690,652
436,912 -> 845,503
32,123 -> 576,667
142,79 -> 741,678
610,228 -> 468,370
172,667 -> 172,736
961,700 -> 132,700
804,875 -> 804,213
71,970 -> 340,970
171,52 -> 149,30
754,604 -> 226,604
485,941 -> 27,941
126,383 -> 328,181
41,39 -> 987,985
128,62 -> 896,830
414,278 -> 923,787
712,15 -> 712,859
794,35 -> 200,629
516,147 -> 402,261
526,862 -> 905,862
721,407 -> 721,887
728,920 -> 339,920
117,417 -> 203,417
291,561 -> 17,835
171,359 -> 837,359
93,125 -> 136,125
220,226 -> 220,177
75,434 -> 75,407
235,664 -> 141,664
553,490 -> 566,477
487,651 -> 487,877
699,150 -> 933,384
73,556 -> 453,556
363,371 -> 363,984
905,106 -> 668,106
139,271 -> 139,125
466,379 -> 466,420
12,935 -> 625,935
89,892 -> 779,892
119,701 -> 270,852
354,886 -> 80,886
917,376 -> 440,376
23,182 -> 794,953
451,718 -> 121,718
62,251 -> 62,451
642,74 -> 642,698
425,200 -> 442,200
828,175 -> 828,405
751,743 -> 591,743
569,681 -> 574,681
329,187 -> 329,837
302,592 -> 302,230
359,135 -> 386,108
44,234 -> 44,731
836,305 -> 836,574
170,512 -> 367,512
576,699 -> 576,44
398,185 -> 821,185
733,78 -> 733,747
141,183 -> 141,787
65,360 -> 65,691
828,780 -> 828,98
776,744 -> 776,751
881,74 -> 481,474
438,642 -> 438,399
676,972 -> 175,972
60,318 -> 56,314
312,169 -> 341,169
736,472 -> 392,128
225,281 -> 164,281
407,799 -> 341,799
458,826 -> 983,301
12,988 -> 987,13
23,854 -> 662,215
82,863 -> 82,416
542,708 -> 542,44
659,51 -> 520,51
353,246 -> 353,90
985,976 -> 77,68
628,493 -> 628,510
51,48 -> 635,48
97,814 -> 828,83
14,44 -> 773,44
603,178 -> 597,178
11,220 -> 783,220
613,39 -> 613,719
68,303 -> 690,925
121,974 -> 896,199
343,54 -> 343,837
744,303 -> 744,942
678,370 -> 246,370
937,134 -> 84,987
357,333 -> 357,516
848,212 -> 429,631
909,244 -> 138,244
122,794 -> 786,130
274,611 -> 57,611
66,337 -> 385,18
847,356 -> 831,356
740,480 -> 740,359
194,443 -> 194,301
50,564 -> 572,42
86,587 -> 774,587
708,258 -> 49,917
420,530 -> 277,387
509,580 -> 509,71
237,196 -> 479,196
442,287 -> 850,287
830,393 -> 532,393
274,720 -> 501,493
610,565 -> 218,957
380,393 -> 380,800
237,847 -> 155,847
267,791 -> 52,791
275,772 -> 275,794
239,238 -> 419,418
200,785 -> 884,101
185,980 -> 185,284
47,46 -> 750,749
724,661 -> 724,337
630,349 -> 666,349
21,911 -> 21,569
661,562 -> 661,925
41,898 -> 41,104
988,67 -> 105,67
739,65 -> 868,65
187,973 -> 809,973
730,211 -> 255,686
254,445 -> 254,872
622,364 -> 235,751
402,980 -> 761,621
46,488 -> 960,488
799,708 -> 799,862
909,181 -> 909,189
450,266 -> 450,304
631,584 -> 631,455
164,830 -> 744,250
679,755 -> 690,744
949,26 -> 190,785
695,783 -> 218,783
269,151 -> 40,151
166,152 -> 22,152
281,819 -> 922,178
956,649 -> 956,593"""
vents2="""0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2"""
size=1000
map = [[0 for x in range(size)] for y in range(size)]
#print(map)
for vent in vents.splitlines():
line = vent.split(" -> ")
x1, y1 = [int(digit) for digit in line[0].split(",")]
x2, y2 = [int(digit) for digit in line[1].split(",")]
if x1 == x2:
y_min = min(y1, y2)
y_max = max(y1, y2)
#print(x1, y_min, y_max)
for y in range(y_min, y_max + 1):
map[y][x1] += 1
elif y1 == y2:
x_min = min(x1, x2)
x_max = max(x1, x2)
#print(y1, x_min, x_max)
for x in range(x_min, x_max + 1):
map[y1][x] += 1
else:
dx = 1 if x2 > x1 else -1
dy = 1 if y2 > y1 else -1
range_x = range(x1, x2 + dx, dx)
range_y = range(y1, y2 + dy, dy)
for y, x in zip(range_y, range_x):
map[y][x] += 1
overlap = 0
for row in map:
for cell in row:
#print(cell)
if cell > 1:
overlap += 1
print("\n".join([",".join([str(digit) for digit in line]) for line in map]))
print(overlap)
|
# Bot's version number
__version__ = "0.1.0"
# Authorized guild
GUILD_ID = 952941520867196958
|
#Rep of loops
numbers = [2, 3, 4, 45]
l = len(numbers)
for i in range(l):
print(numbers[i]) # each iteration the i takes on a different
#value according to len of numbers (4)
for i in range(8):
print(i) # prints numbers 0 through 7
for el in numbers:
print(el)
# using a loop to change elements within a list
items = ['yellow', 'red', 'green', 'purple', 'blue'] #list of colours
for i in range(5):
print('Before item ', i , 'is', items[i])
items[i] = 'different'
print('After item ', i , 'is', items[i])
items = ['yellow', 'red', 'green', 'purple', 'blue'] #list of colours
for index_of_enumerate, colors in enumerate(items):
print(index_of_enumerate, colors)
# while:
months = ['june', 'august', 'july', 'may']
i = 0
month = 'a'
while month != 'august':
month = months[i]
print(month)
i += 1
# Write your code below and press Shift+Enter to execute
# Write a while loop to display the values of the Rating of an album playlist stored in the list PlayListRatings. If the score is less than 6, exit the loop. The list PlayListRatings is given by: PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
i = 0
score = PlayListRatings[i]
#print(score)
while score >= 6:
score = PlayListRatings[i]
print(score)
i += 1
|
"""
cheesyutils - A number of utility packages and functions
"""
__title__ = "cheesyutils"
__author__ = "CheesyGamer77"
__copyright__ = "Copyright 2021-present CheesyGamer77"
__version__ = "0.0.30"
|
def append_text(new_text):
'''
Write the code instruction to be exported later on
Args.
new_text (str): the text that will be appended to the base string
'''
global code_base_text
code_base_text = code_base_text + new_text
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.