content stringlengths 7 1.05M |
|---|
height_map = ["".join(["9", line.rstrip(), "9"]) for line in open("input.txt", "r")]
height_map.insert(0, len(height_map[0])*"9")
height_map.append( len(height_map[0])*"9")
len_x, len_y = len(height_map), len(height_map[0])
risk_level_sum = 0
for x in range(1, len_x-1):
for y in range(1, len_y-1):
height ... |
def encode(message):
a = [message[0]]
b = []
count = 0
message+="1"
for x in message[1:]:
if a[-1] == x:
count+=1
else:
count+=1
b.append((a[-1],count))
count = 0
a.append(x)
encoded_message = ""
for x,y in b:
e... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : mh
class Person(object):
def __init__(self):
self.name = None
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def greet(self):
print('peoson 名字: {}', format(self.name))
|
class Student(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return "A student with " + self.user_email + " is attending a seminar"
class Teacher(object):
def __init__(self, user_email):
self.user_email = user_email
def some_actio... |
def gcd(a,b):
if a==0:
return b
elif b==0:
return a
elif b>a:
return gcd(b,a)
else:
return gcd(b,a%b)
t = int(input())
for i in range(t):
n = int(input())
for j in range(n):
l = list(map(int, input().split()))
print(l) |
#!/usr/bin/python
########################################################################
# Copyright (c) 2014
# Christopher Kannen <ckannen<at>uni-bonn<dot>de>
# Daniel Plohmann <daniel.plohmann<at>gmail<dot>com>
# All rights reserved.
########################################################################
#
# This... |
#
# @lc app=leetcode id=22 lang=python3
#
# [22] Generate Parentheses
#
# @lc code=start
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 1:
return ['()']
last_parenthesis = self.generateParenthesis(n - 1)
stack = []
for parenthesis in last_p... |
def bifurcate(lst, filter):
return [
[x for i,x in enumerate(lst) if filter[i] == True],
[x for i,x in enumerate(lst) if filter[i] == False]
]
print(bifurcate(['beep', 'boop', 'foo', 'bar',], [True, True, False, True]))
|
class SearchException(Exception):
pass
class SearchSyntaxError(SearchException):
def __init__(self, msg, reason='Syntax error'):
super(SearchSyntaxError, self).__init__(msg)
self.reason = reason
class UnknownField(SearchSyntaxError):
pass
class UnknownOperator(SearchSyntaxError):
pas... |
class DirectedGraph:
"""Simple directed graph mapping from any -> any"""
def __init__(self):
self._nodes = set()
self._outputs = dict()
self._inputs = dict()
@property
def nodes(self):
return self._nodes
def inputs(self, n):
return self._inputs.get(n, set... |
#!/usr/bin/python3
'''
Implementação simplificada do map
'''
def mapear(funcao, lista):
for elemento in lista:
yield funcao(elemento)
if __name__ == "__main__":
resultado = mapear(lambda x: x ** 2, [2, 3, 4])
print(list(resultado))
# Fontes:
# Curso Python 3 - Curso Completo do Básico ao Av... |
counter = 0
def even_customers():
return counter%2==0
def incoming():
global counter
counter+=1
def outgoing():
global counter
if(counter > 0):
counter-=1
|
"""Exceptions"""
class ModelConfigError(Exception):
"""Base error class for config files"""
|
# Problem description: Given two linked lists, return the node where the intersection begins, or if there's
# no intersection, return null.
# Solution time complexity: O(n)
# Comments: The solution with length offset. This solution makes use of the fact that if distance
#... |
class NoDataException(Exception):
pass
class BadAuthorization(Exception):
pass
|
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
n=int(input('Qual o primeiro termo de uma PA? '))
r=int(input('Qual a razão da sua PA? '))
termo=n
cont=1
total=0
mais=5
while mais!=0:
total= total+ mais
while cont<=total:
print(termo)
termo+=r
cont=cont+1
print('pausa')
mais=int(input('Quantos termos você quer mostra? '))
pr... |
ROMAN_TO_INT = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
class Solution:
def recursive_roman_to_int(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
if length == 0:
return 0
elif len... |
def generate_matrix(n):
results = [[0 for i in range(n)] for i in range(n)]
left = 0
right = n - 1
up = 0
down = n - 1
current_num = 1
while left < right and up < down:
for i in range(left, right + 1):
results[up][i] = current_num
current_num += 1
fo... |
class RuntimeConfig:
def __init__(self):
self.items = {}
def add_item(self, item: dict):
"""
Add an item to the runtime config
"""
self.items.update(item)
def get(self, key: str):
"""
Get specific item from config. Returns None if key doesn't exist.... |
"""
Crie um programa que tenha uma Tupla totalmente preenchida com uma contagem por extenso,
de zero até vinte.
Seu programa devera ler um numero pelo teclado(entre 0 e 20) e mostra-lo por extenso.
"""
numeros = ('Zero', 'Um', 'Dois', 'Tres', 'Quatro', 'Cinco', 'Seis',
'Sete', 'Oito', 'Nove', 'Dez', 'Onze',... |
# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other
# Hatchet Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
dot_keywords = ["graph", "subgraph", "digraph", "node", "edge", "strict"]
|
price_of_one_shovel, denomination_of_special_coin = map(int, input().split())
number_of_coins = 0
while True:
number_of_shovels1 = (10 * number_of_coins + denomination_of_special_coin) / price_of_one_shovel
number_of_shovels2 = 10 * (number_of_coins + 1) / price_of_one_shovel
if number_of_shovels1 % 1 == ... |
print('=' * 12 + 'Desafio 84' + '=' * 12)
info = []
temp = []
resp = 'S'
menor = -1
maior = -1
contador = 0
while resp in 'sS':
temp.append(input('Digite o nome: '))
temp.append(float(input('Digite o peso: ')))
info.append(temp[:])
if menor == -1:
menor = temp[1]
maior = temp[1]
if t... |
# BSD 3-Clause License
#
# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyrig... |
# https://leetcode.com/problems/defanging-an-ip-address/
'''
"1.1.1.1"
"1[.]1[.]1[.]1"
"255.100.50.0"
"255[.]100[.]50[.]0"
'''
def defang_ip_address(address):
address_chars_list = []
for char in address:
if char == '.':
address_chars_list.append('[.]')
else:
address_... |
print("How old are you?",end=' ')
age =input()
print("How tell are you?",end=' ')
height =input()
print("How much do you weight?",end=' ')
weight =input()
print("So, you're %r old, %r tall and %r heavy."%(age, height, weight))
|
iterable = [1,2,3]
iterator = iter(iterable)
print( next(iterator) )
print( next(iterator) )
print( next(iterator) ) |
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
lineslist=[]
emaildict={}
for line in fhand:
lineslist = line.split()
if line.startswith('From '):
email=lineslist[1]
if email not in emaildict:
emaildict[email] = 1
else:
... |
"""
mujer--> m-->int
hombre--> h-->int
"""
#entradas
m=int(input("Colocar cantidad de hombres "))
h=int(input("Colocar cantidad de mujeres "))
#Caja negra
p=(m+h)
Mi=(m*100)/p
Pi=(h*100)/p
#Salida
print("El promedio de mujeres es: ", Mi,"%")
print("El promedio de hombres: ", Pi,"%")
|
"""Put your shared fixtures here.
They will be automatically shared between all tests.
"""
|
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n")
base = int(input("Enter the length of the base: "))
height = int(input("Enter the length of the height: "))
print("The area of the triangle is:", 0.5 * base * height) |
# Создать класс Payment (зарплата). В классе должны быть представлены поля: фамилия-
# имя-отчество, оклад, год поступления на работу, процент надбавки, подоходный налог,
# количество отработанных дней в месяце, количество рабочих дней в месяце, начисленная и
# удержанная суммы. Реализовать методы:
# вычисления начисле... |
def determineTime(arr):
totalSec = 0
for a in arr:
(h, m, s) = a.split(':')
totalSec += (int(h) * 3600 + int(m) * 60 + int(s))
return (24 * 60 * 60) > totalSec |
class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
# Runtime: 16 ms
# Memory: 13.1 MB
return address.replace(".", "[.]")
|
# average of elements:
def average():
list_numbers = [25, 45, 12, 45, 85, 25]
print("This is the given list of numbers: ")
print(list_numbers)
total = 0
for i in list_numbers:
total += i
total /= len(list_numbers)
print(f"The average of the numbers are: {total}")
average()
|
class EnergyAnalysisOpening(Element,IDisposable):
""" Analytical opening. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def GetAnalyticalSurface(self):
"""
GetAnalyticalSurface(self: EnergyAnalysisOpening) -> EnergyAnalysisSurface
Gets the associative analytical parent... |
#!/usr/bin/env python
# pylint: disable=W0212
def limit(self, start_or_stop=None, stop=None, step=None):
"""
Create a new table with fewer rows.
See also: Python's builtin :func:`slice`.
:param start_or_stop:
If the only argument, then how many rows to include, otherwise,
the index o... |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_codehaus_plexus_plexus_archiver",
artifact = "org.codehaus.plexus:plexus-archiver:3.4",
artifact_sha256 = "3c6611c98547dbf3f5125848c273ba719bc10df44e3f492fa2e30... |
# Solution 1
# O(n) time / O(1) space
def indexEqualsValue(array):
for index in range(len(array)):
value = array[index]
if index == value:
return index
return -1
# Solution 2 - recursion
# O(log(n)) time / O(log(n)) space
def indexEqualsValue(array):
return indexEqualsValueH... |
value_l = ['название', 'цена', 'количество', 'единица измерения']
l = []
n = 'y'
i = 0
while n == 'y':
d = {}
i += 1
for value in value_l:
d[value] = input(f'Введите {value}: ')
l.append((i, d))
n = input('Для ввода еще одного элемента в список, нажмите y: ').lower()
print(f'Введен список: {... |
def near_hundred(n):
if 90 <= n <=110 or 190 <= n <= 210:
return True
else:
return False
result = near_hundred(93)
print(result)
result = near_hundred(90)
print(result)
result = near_hundred(89)
print(result)
result = near_hundred(190)
print(result)
result = near_hundred(210)
print(result... |
#!/usr/bin/python
__author__ = "Bassim Aly"
__EMAIL__ = "basim.alyy@gmail.com"
# sudo scapy
# send(IP(dst="10.10.10.1")/ICMP()/"Welcome to Enterprise Automation Course")
|
# coding: utf-8
__all__ = [
"__package_name__",
"__module_name__",
"__copyright__",
"__version__",
"__license__",
"__author__",
"__author_twitter__",
"__author_email__",
"__documentation__",
"__url__",
]
__package_name__ = "PyVideoEditor"
__module_name__ = "veditor"
__copyright... |
"""
Smirk - Web Application Framework
Copyright (c) 2016 Brett Fraley
Source Repository
https://github.com/bFraley/Smirk
MIT License
https://github.com/bFraley/Smirk/blob/master/LICENSE
File: service_event.py
About: Generic service event type used to build many types of
service events. The ServicesProcessor manages... |
def main():
project()
# extracredit()
# Create a task list.
# A user is presented with the text below.
# Let them select an option to list all of their tasks,
# add a task to their list,
# delete a task,
# or quit the program.
# Make each option a different function in your program.
# Do NOT use Google. Do NOT ... |
class BaseConfig(object):
"""Base configuration."""
WTF_CSRF_ENABLED = True
REDIS_URL = "redis://redis:6379"
QUEUES = ["default"]
# Exchanges
# BINANCE_KEY = os_get("BINANCE_KEY")
# BINANCE_SECRET = os_get("BINANCE_SECRET")
# BITMEX_KEY = os_get("BITMEX_KEY")
# BITMEX_SECRET = os_get... |
####################################################################################
# BLACKMAMBA BY: LOSEYS (https://github.com/loseys)
#
# QT GUI INTERFACE BY: WANDERSON M.PIMENTA (https://github.com/Wanderson-Magalhaes)
# ORIGINAL QT GUI: https://github.com/Wanderson-Magalhaes/Simple_PySide_Base
####################... |
calculation_to_units = 24 # global vars
name_of_unit = "hours" # global vars
def days_to_units(num_of_days, custom_message):
# num_of_days and custom_message are local vars inside function
print(f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}")
print(custom_message)
def s... |
class Problem:
MULTI_LABEL = 'MULTI_LABEL'
MULTI_CLASS = 'MULTI_CLASS'
GENERIC = 'GENERIC'
class AssignmentType:
CRISP = 'CRISP'
CONTINUOUS = 'CONTINUOUS'
GENERIC = 'GENERIC'
class CoverageType:
REDUNDANT = 'REDUNDANT'
COMPLEMENTARY = 'COMPLEMENTARY'
COMPLEMENTARY_REDUNDANT = 'CO... |
N,M = map(int,input().split())
ab_lst = [list(map(int,input().split())) for i in range(M)]
K = int(input())
cd_lst = [list(map(int,input().split())) for i in range(K)]
|
# hello.py
print('Hello World')
# python hello.py
# Hello World |
# O usuário deve digitar dois valores e o programa deve identificar se os valores são iguais ou diferentes#
def compare(a, b):
if (a==b):
print('Os números são iguais')
else:
print('Os números são diferentes')
n1 = int(input('Digite um número:'))
n2 = int(input('Digite outro número:'))
compa... |
'one\n'
'two\n'
'threefourfive\n'
'six\n'
'seven\n'
'last'
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# Copyright (C) 2019 Akamai Technologies, Inc.
# Copyright (C) 2011-2014,2016 Nominum, Inc.
#
# 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-... |
KAGGLE_SERVER_ID = 862766322550702081
SPAM_TIME = 5 # number of seconds between messages in the same channel
SPAM_AMOUNT = 5 # number of messages sent in or less :SPAM_TIME:
# seconds to be considered spam
SPAM_PUNISH_TIME = 10
MUTE_ROLE_ID = 12345 # ID of the role to use to mute members.
DATAB... |
'''
* Criar variaveis para nome(str), idade(int),
* altura (float), e peso (float) de uma pessoa
* Criar variavel como o ano atual (int)
* Obter o ano de nascimento da pessoa (baseado na idade e ano atual da pessoa)
* Exibir um texto com todos os valores na tela usando f-string (com as chaves).
'''
nome = 'Dilson'
idad... |
# --------------
#Code starts here
#Function to read file
def read_file(path):
file = open(path, 'r')
scentence = file.readline()
file.close()
return scentence
path = file_path
sample_message = read_file(path)
print (sample_message)
message_1 = read_file(file_path_1)
print (message_1)
me... |
#
# PySNMP MIB module MY-MEMORY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MY-MEMORY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:16:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
for i in range(1,9):
print(i)
a=2
b=1
print(a,b)
#print a
|
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('GUESS: '))
guess_count += 1
if guess == secret_number:
print('YOU WON!')
break
else:
print("SORRY YOU DID NOT GUESS THE CORRECT WORD") |
class Employee:
company = "Google"
salary = 100
location = "Delhi"
@classmethod
def changeSalary(cls,sal):
cls.salary = sal
print(f"The salary of the employee is {cls.salary}")
e = Employee()
e.changeSalary(455)
print(e.salary)
Employee.salary = 500
print(Employee.sal... |
def get_children(S, root, parent):
"""returns the children from following the
green edges"""
return [n for n, e in S[root].items()
if ((not n == parent) and
(e == 'green'))]
d = get_children(
{'a':{'b':1},
'b':{'c':1},
'c':{'d':1},
'd':{'e':1}
}, 'a','b')
p... |
# -*- coding:utf-8 -*-
##############################################################
# Created Date: Tuesday, December 29th 2020
# Contact Info: luoxiangyong01@gmail.com
# Author/Copyright: Mr. Xiangyong Luo
##############################################################
def writeTest(msg):
print(msg)
def wr... |
l = [{'key': 300}, {'key': 200}, {'key': 100}]
print(l)
l.sort(key = lambda x: x['key'])
print(l)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class MappingDocuments(object):
def __init__(self):
self.work_dir = None
self.download_path = None
self.ole_path = None
self.id = None
self.case_id = None
self.case_name = None
self.evdnc_id = None
self.evdnc_name = None
self.doc_id = None
self.doc... |
num_0 = [
[1, 1, 1],
[1, 0, 1],
[1, 0, 1],
[1, 0, 1],
[1, 1, 1]
]
num_1 = [
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]
]
num_2 = [
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[1, 0, 0],
[1, 1, 1]
]
num_3 = [
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
num_4 = [
[1, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1]... |
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
n = max(len(a), len(b))
a = a.zfill(n)
b = b.zfill(n)
carry = 0
answer = []
for i in range(n - 1, -1, -1):
if a[i] == '... |
info = {
"UNIT_NUMBERS": {
"nulle": 0,
"viena": 1,
"viens": 1,
"divas": 2,
"divi": 2,
"trīs": 3,
"četras": 4,
"četri": 4,
"piecas": 5,
"pieci": 5,
"sešas": 6,
"seši": 6,
"septiņas": 7,
"septiņi": 7,
... |
class Application:
def __init__(self,expaid,url,status,currentStatus,personid,oppid):
self.id = expaid
self.url=url
self.status=status
self.currentStatus=currentStatus
self.personid=personid
self.oppid=oppid
|
n = []
while True:
try:
i = float(input('Enter a number or Enter to finish: '))
except:
break
else:
n.append(i)
print(f'Numbers: {n}')
print(f'''Count: {len(n)}
Sum: {sum(n)}
Highest: {max(n)}
Lowest: {min(n)}
Mean: {sum(n)/len(n)}
''') |
class Node:
def __init__(self, data=None):
self.__data = data
self.__next = None
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def next(self):
return self.__next
@next.setter
de... |
# Description: Color unit cell edges black. The settings for controlling the unit cell color are hard to find.
# Source: placeHolder
"""
cmd.do('# show the unit cell;')
cmd.do('show cell;')
cmd.do('color black, ${1:1lw9};')
cmd.do('# color by atom with carbons colored green,')
cmd.do('util.${2:cbag};')
cmd.do('set c... |
value = 1
end = 10
while (value < end):
print(value)
value = value + 1
if (value == 5):
break |
"""
>>> from mlbase.event import event_manager
>>> @event_manager.on("A")
... def _():
... print('Hello')
>>> @event_manager.on("B")
... def _():
... print('World')
>>> event_manager.emit("A")
Hello
>>> event_manager.emit("B")
World
"""
class EventManager:
def __init__(self):
self._event_dict = {}
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# l-1: 可复用性较差, 没有返回
def fab(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
fab(5)
print("-------1------ ")
# l-2: 内存占用
def fab2(max):
n, a, b = 0, 0, 1
L = []
while n < max:
L.append(b)
... |
pala = ('APRENDER',
'PROGRAMAR',
'LINGUAGEM',
'PYTHON',
'CURSO',
'GRATIS',
'ESTUDAR',
'PRATICAR',
'TRABALHAR',
'MERCADO',
'PROGRAMADOR',
'FUTURO')
for p in pala:
print(f'\nNa palavra {p} temos', end=' ')
for letra in p:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/)
FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the
terms of the MIT License as published by the Free Software Foundation. This proje... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
profit = 0
buy = 9999999999999
for i,j in enumerate (prices):
if j<buy:
buy = j
else:
if j>buy:
profit = max(... |
################################################################################
level_number = 13
dungeon_name = 'The Tower'
wall_style = 'Mangar'
monster_difficulty = 6
goes_down = False
entry_position = (255, 255)
phase_door = False
level_teleport = [
(11, True),
(12, True),
(13, True),
(14, False),... |
''' Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$ 0,50 por Km para viagens de até 200 Km e R$ 0,45 parta viagens mais longas. '''
distancia = float(input('Qual a distância da viagem em Km? '))
print(f'Você está prestes a começar sua viagem de {distancia:.... |
def limpiarString(stringin):
punt = ''':/,-.'"}{)(;]['''
for char in stringin:
if char in punt:
stringin = stringin.replace(char, " ")
return stringin
def formatearALista(stringin):
stringin=stringin.lower()
stringin=limpiarString(stringin)
return stringin.split()
nombres... |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/college"
# docs_base_url = "https://[org_name].github.io/college"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "college"
|
# Given a binary tree, return the level of the tree with minimum sum.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def min_level_sum(node):
min_sum = float('inf')
cur_levle = [node]
while cur... |
#PREPARACION CUARTO LABORATORIO
#EJERCICIO 1:
def obtener_cadena():
cadena=input("Ingrese cadena deseada: ")
if cadena != "fin":
if len(cadena)<1:
print("ingrese al menos un caracter: ")
cadena=input("Ingrese cadena deseada: ")
if "1" in cadena or "2" in caden... |
def comboboxListOptions(window_struct, object_struct,handle=None):
if handle == None:
result = getObject(window_struct,object_struct)
handle = result['handle']
list_options=[]
if handle.getChildCount() > 0:
for childlvl_1 in range(0,handle.getChildCount()):
cur_handle_ch... |
class Foo(object):
A = 1
B = 2
def __init__(self):
self.class_var = "V"
def main():
f = Foo()
g = Foo()
f.A = 12
g.A = 33
Foo.A = 34
print("f.A: {}".format(f.A))
print("g.A: {}".format(g.A))
print("Foo.A: {}".format(Foo.A))
print("f.class_var: {}".format(f.class_var))
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
@Time 15/05/2018 11:41 AM 2018
@Author HJ@USTC
@Email jhsa26@mail.ustc.edu.cn
@Blog jhsa26.github.io
"""
class Config(object):
def __init__(self):
# self.filepath_disp_training = '../DataSet/TrainingData/0.5km/China/disp_combine_gaussian_map_5-10/'
... |
"""Configures the node dependencies for the markdown functionality."""
load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories", "yarn_install")
def markdown_register_node_deps(name = "cgrindel_bazel_starlib_markdown_npm"):
"""Configures the installation of the Javascript node dependencies for the markdo... |
#Answer Key
#1.1
print (100 * 1.02 ** 8)
#1.2
pig3 = "2.85"
print(type(pig3))
float(pig3)
print(pig3)
#1.3
hall = 6.25
kit = 11.0
liv = 40.0
bed = 17.75
bath = 11.50
# Adapt list areas
areas = [str("hallway"),hall, "kitchen", kit, str("living room"), liv, "bedroom",bed, str("bathroom"),bath]
#Still need to convert to... |
favorite_languages = {
'jen': 'Python',
'sarah': 'C',
'edward': 'Ruby',
'phil': 'Python'
}
for name in favorite_languages.keys():
print(name.title())
for value in favorite_languages.values():
print(value.title())
# print(f"\n Sarah's favorite languages is " + favorite_languages['sarah'].title... |
class rectangle():
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def area(self):
return self.length * self.breadth
a = int(input("Enter length of rectangle : "))
b = int(input("Enter a breadth of rectangle : "))
obj = rectangle(a, b)
print("Area of rect... |
# Program to check if a is a primitive root mod q
# Written by Benjamin Mestdagh
def calculate(a, q):
powers = []
for i in range(1, q):
result = (a**i) % q
if result in powers:
return False
else:
powers.append(result)
return True
try:
a = int(input("En... |
"""
- Where Does Async IO Fit In?
Concurrency and parallelism are expansive subjects that are not easy to wade
into. While this tutorial focuses on async IO and its implementation in Python,
it’s worth taking a minute to compare async IO to its counterparts in order to
have context about how async IO fits into the ... |
nums=[2,3,3,4]
def combines(nums):
assert(nums)
if len(nums) == 1:
return [(nums[0], [])]
out = []
for i in range(1,len(nums)):
for j in range(i):
n1 = nums[j]
n2 = nums[i]
if nums.index(n1) != j:
continue
if nums.index(n2) ... |
df_referendum['Department code'] = df_referendum['Department code'].apply(
lambda x: '0' + x if len(x) == 1 else x
)
df_referendum.head()
|
size = int(input())
matrix = [
[int(_) for _ in input().split()]
for i in range(size)
]
bombs = [_.split(",") for _ in input().split()]
for bomb in bombs:
current_bomb = matrix[int(bomb[0])][int(bomb[1])]
c_b_row = int(bomb[0])
c_b_col = int(bomb[1])
damage = current_bomb
around_squares = ... |
description = 'resolution args of chopper real table'
group = 'lowlevel'
includes = ['chopper', 'detector', 'real_flight_path']
devices = dict(
resolution = device('nicos_mlz.refsans.devices.resolution.Resolution',
description = description,
chopper = 'chopper',
flightpath = 'real_flight_... |
def main():
# input
N = int(input())
As = [*map(int, input().split())]
# compute
studentss = []
for i, A in enumerate(As):
studentss.append([A, i])
anss = []
for _, num in sorted(studentss):
anss.append(num + 1)
# output
print(*anss)
if __name__ == '__main__':... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.