content stringlengths 7 1.05M |
|---|
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
cycle = 2*(numRows-1)
if numRows == 1: cycle = 1
map = []
for i in range(numRows):
map.append('')
for j ... |
class Solution:
def maxLength(self, arr) -> int:
def helper(word):
temp=[]
temp[:0]=word
res=set()
for w in temp:
if w not in res:
res.add(w)
else:
return None
return res
... |
class Node(object):
def __init__(self, name):
self.name = name;
self.adjacencyList = [];
self.visited = False;
self.predecessor = None;
class BreadthFirstSearch(object):
def bfs(self, startNode):
queue = [];
queue.append(startNode);
startNode.visited = True;
# BFS -> queue ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 15 11:31:06 2021
@author: a77510jm
"""
|
###############################################################
#
# This function is... INSUFFICIENT. It was developed as an
# illustration of EDA lessons in the 2021 class. It's quick and
# works well.
#
# Want a higher grade version of me? Then try pandas-profiling:
# https://github.com/pandas-profiling/pandas-... |
"""
Simple math operating functions for unit test
"""
def add(a, b):
"""
Adding to parameters and return result
:param a:
:param b:
:return:
"""
return a + b
def minus(a, b):
"""
subtraction
:param a:
:param b:
:return:
"""
return a - b
def multi(a, b):
... |
"""
flags.py
. should be renamed helpers...
. This file is scheduled for deletion
"""
"""
valid accessory tags:
"any_tag": {"code": "code_insert_as_string"} # execute arbitrary code to construct this key.
"dialect": csv.excel_tab # dialect of the file, default = csv, set this to use tsv. or sniffer
"skip_lines": num... |
# это dev среда
TELEGRAM_TOKEN = "..."
RELATIVE_CHAT_IDS = [ "...", '...']
TEXT = {
"bot_info": ('Привет, я бот, который отвечает за равномерное распределение участников по комнатам.\n\n'
'Нажми кнопку, если готов сменить комнату'),
"get_link": "Получить рекомендацию",
"new_room": "Ваша н... |
def get(isamAppliance, check_mode=False, force=False):
"""
Retrieve an overview of updates and licensing information
"""
return isamAppliance.invoke_get("Retrieve an overview of updates and licensing information",
"/updates/overview")
def get_licensing_info(isamAppl... |
"""Top-level package for etherscan-py."""
__author__ = """Julian Koh"""
__email__ = 'juliankohtx@gmail.com'
__version__ = '0.1.0'
|
# UC10 - Evaluate price
#
# User U exists and has valid account
# We create two Users, User1_UC10, User2_UC10 and one new gasStation GasStationUC10
#
# Registered on a 1920x1080p, Google Chrome 100% zoom
### SETUP
#User1
click("1590678880209.png")
click("1590678953637.png")
wait(2)
type("1... |
self.description = "Install a package ('any' architecture)"
p = pmpkg("dummy")
p.files = ["bin/dummy",
"usr/man/man1/dummy.1"]
p.arch = 'any'
self.addpkg(p)
self.option["Architecture"] = ['auto']
self.args = "-U %s" % p.filename()
self.addrule("PACMAN_RETCODE=0")
self.addrule("PKG_EXIST=dummy")
for f in ... |
"""
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Implement a stack that has the following methods:
push(val), which pushes an element onto the stack
pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it sh... |
x:[int] = None
x = []
print(x[0])
|
def remove_duplicates(lst):
new = []
for x in lst:
if x not in new:
new.append(x)
return new
|
class Config:
# helps to store settings for an experiment.
def __init__(self, _experiments_folder_path='experiments', _dataset_name='dataset', _column_names='unknown',
_types={1:'integer', 2:'string', 3:'float', 4:'boolean', 5:'gender', 6:'unknown', 7:'date-iso-8601', 8:'date-eu', 9:'date-non-s... |
data = (
'Lun ', # 0x00
'Kua ', # 0x01
'Ling ', # 0x02
'Bei ', # 0x03
'Lu ', # 0x04
'Li ', # 0x05
'Qiang ', # 0x06
'Pou ', # 0x07
'Juan ', # 0x08
'Min ', # 0x09
'Zui ', # 0x0a
'Peng ', # 0x0b
'An ', # 0x0c
'Pi ', # 0x0d
'Xian ', # 0x0e
'Ya ', # 0x0f
'Zhui ', # 0x10
'Le... |
def three_sum(nums):
"""
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
:param nums: list[int]
:return: list[list[int]]
"""
if len(nums) < 3:
return []
nums.sort()
... |
class Allergies(object):
def __init__(self, score):
pass
def allergic_to(self, item):
pass
@property
def lst(self):
pass
|
#
# PySNMP MIB module CISCO-IETF-PW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IETF-PW-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:43:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
_base_ = [
'../_base_/models/fpn_r50.py', '../_base_/datasets/onaho.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
model = dict(decode_head=dict(num_classes=2))
|
def get_default_convnet_setting():
net_width, net_depth, net_act, net_norm, net_pooling = 128, 3, 'relu', 'instancenorm', 'avgpooling'
return net_width, net_depth, net_act, net_norm, net_pooling
def get_loops(ipc):
# Get the two hyper-parameters of outer-loop and inner-loop.
# The following values are ... |
"""
Space : O(1)
Time : O(n)
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
start, dp = 10**10, 0
for i in prices:
print(start)
start = min(start, i)
dp = max(dp, i-start)
return dp
|
# node to capture and communicate game status
# written by Russell on 5/18
class Game_state():
node_weight = 1
# node_bias = 1 # not going to use this for now, but may need it later
list_of_moves = []
def __init__(self, node_list):
self.node_list = node_list
def num_moves(self):
... |
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if len(intervals) <= 1:
... |
class myIntSynthProvider(object):
def __init__(self, valobj, dict):
self.valobj = valobj
self.val = self.valobj.GetChildMemberWithName("theValue")
def num_children(self):
return 0
def get_child_at_index(self, index):
return None
def get_child_index(self, name):
... |
# Say you have an array for which the ith element is the price of a given stock on day i.
# Design an algorithm to find the maximum profit. You may complete at most two transactions.
# Note: You may not engage in multiple transactions at the same time
# (i.e., you must sell the stock before you buy again).
# Example ... |
# -*- coding: utf-8 -*-
"""Module init code."""
__version__ = '0.0.0'
__author__ = 'Your Name'
__email__ = 'your.email@mail.com'
|
"""
Hydropy
=======
Provides functions to work with hydrological processes and equations
"""
|
"""
Desafio
Você recebeu o desafio de ler um valor e criar um programa que coloque o valor lido na primeira posição de um vetor N[10].
Em cada posição subsequente, coloque o dobro do valor da posição anterior.
Por exemplo, se o valor lido for 1, os valores do vetor devem ser 1,2,4,8 e assim sucessivamente.
Mostre o ... |
# Яке з 3 чисел найбільш наближене до середнього
print("Введіть перше число")
var1 = float(input())
print("Введіть друге число")
var2 = float(input())
print("Введіть третє число")
var3 = float(input())
# Avg = (var1+var2+var3)/3 # Варіант розв'язку з порівнянням чисел із середнім арифметичним:
if ((var1 > var... |
class Photo:
def __init__(self, lid, tags_list, orientation):
"""
Constructor
:param lid: Photo identifier
:param tags_list: List of tags
:param orientation: Orientation. "H" for horizontal or "V" for vertical
"""
self.id = lid
self... |
'''
Test HTTP/2 with h2spec
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version... |
# Dependency injection:
# Technique where one object (or static method) supplies the dependencies of another object.
# The objective is to decouple objects to the extent that no client code has to be changed
# simply because an object it depends on needs to be changed to a different one.
# Dependency injection is one f... |
"""
235. Lowest Common Ancestor of a Binary Search Tree
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
... |
def conv(s):
if s[0] == 'a': v = '1'
elif s[0] == 'b': v = '2'
elif s[0] == 'c': v = '3'
elif s[0] == 'd': v = '4'
elif s[0] == 'e': v = '5'
elif s[0] == 'f': v = '6'
elif s[0] == 'g': v = '7'
elif s[0] == 'h': v = '8'
v += s[1]
return v
e = str(input()).split()
a = conv(e[0])
b... |
#!/usr/bin/env python
domain_home = os.environ['DOMAIN_HOME']
node_manager_name = os.environ['NODE_MANAGER_NAME']
component_name = os.environ['COMPONENT_NAME']
component_admin_listen_address = os.environ['COMPONENT_ADMIN_LISTEN_ADDRESS']
component_admin_listen_port = os.environ['COMPONENT_ADMIN_LISTEN_PORT']
component... |
# https://github.com/ArtemNikolaev/gb-hw/issues/18
seasons = [
'ЗИМА',
'ВЕСНА',
'ЛЕТО',
'ОСЕНЬ'
]
month = int(input('Введите номер месяца: '))
if month < 1 or month > 12:
print('Месяцев всего 12. Поэтому минимальное значение - 1, а максимальное - 12')
else:
seasonInt = (month % 12) // 3
p... |
"""
@generated
cargo-raze generated Bazel file.
DO NOT EDIT! Replaced on runs of cargo-raze
"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # buildifier: disable=load
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # buildifier: disable=load
load("@bazel_tools//too... |
#Exercise: Try to make a function that accepts a function of only positional arguments and returns a function that takes the same number of positional arguments and, given they are all iterators, attempts every combination of one arguments from each iterator.
#Skills: Partial application, Iteration
papplycomboreverse ... |
class Node:
"""
This object is a generic node, the basic component of a Graph.
Fields:
data -- the data this node will contain. This data can be any format.
"""
def __init__(self, data):
self.data = data
|
"""
Global tuple to avoid make a new one each time a method is called
"""
my_tuple = ("London", 123, 18.2)
def city_tuple_declaration():
city = ("Rome", "London", "Tokyo")
return city
def tuple_get_element(index: int):
try:
element = my_tuple[index]
print(element)
except IndexError:
... |
# https://leetcode.com/problems/mirror-reflection
class Solution:
def mirrorReflection(self, p, q):
if q == 0:
return 0
i = 0
val = 0
while True:
val += q
i += 1
if (i % 2 == 0) and (val % p == 0):
return 2
... |
"""
The `~certbot_dns_cfproxy.dns_cfproxy` plugin automates the process of
completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and
subsequently removing, TXT records using the CFProxy API.
Examples
--------
.. code-block:: bash
:caption: To acquire a certificate for ``example.com``
certbo... |
a, b = map(int, input().split())
if a+b >= 10:
print("error")
else:
print(a+b)
|
__version__ = [1, 0, 2]
__versionstr__ = '.'.join([str(i) for i in __version__])
if __name__ == '__main__':
print(__versionstr__) |
flat_x = x.flatten()
flat_y = y.flatten()
flat_z = z.flatten()
size = flat_x.shape[0]
filename = 'landscapeData.h'
open(filename, 'w').close()
f = open(filename, 'a')
f.write('#include "LinearMath/btScalar.h"\n#define Landscape01VtxCount 4\n#define Landscape01IdxCount 4\nbtScalar Landscape01Vtx[] = {\n')
for i in r... |
voc_it = [
['a', 'noun', 'c'],
['a', 'preposition', 'a'],
['abbagliante', 'pres_part', 'c'],
['abbagliante', 'adjective', 'c'],
['abbagliante', 'noun', 'c'],
['abbaiare', 'verb', 'c'],
['abbandonare', 'verb', 'a'],
['abbandonato', 'past_part', 'b'],
['abbandonato', 'adjective', 'b'],
['abbandono', 'noun', 'b'],
['abbas... |
# coding=utf-8
"""Russian Peasant Multiplication algorithm Python implementation."""
def russ_peasant(a, b):
res = 0
while b > 0:
if b & 1:
res += a
a <<= 1
b >>= 1
return res
if __name__ == '__main__':
for x in range(10):
for y in range(10):
p... |
"""
QuickBot wiring config.
Specifies which pins are used for motor control, IR sensors and wheel encoders.
"""
# Motor pins: (dir1_pin, dir2_pin, pwd_pin)
RIGHT_MOTOR_PINS = 'P8_12', 'P8_10', 'P9_14'
LEFT_MOTOR_PINS = 'P8_14', 'P8_16', 'P9_16'
# IR sensors (clock-wise, starting with the rear left sensor):
# rear-l... |
# Illustrates combining exception / error handling
# with file access
print('Start')
try:
with open('myfile2.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line, end='')
except FileNotFoundError as err:
print('oops')
print(err)
print('Done')
|
disable_gtk_binaries = True
def gtk_dependent_cc_library(**kwargs):
if not disable_gtk_binaries:
native.cc_library(**kwargs)
def gtk_dependent_cc_binary(**kwargs):
if not disable_gtk_binaries:
native.cc_binary(**kwargs)
|
# Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.
# Make sure your procedure has a return statement.
def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
def... |
#!/usr/local/bin/python3
def main():
# Test suite
return
if __name__ == '__main__':
main()
|
def LeiaInt(msg1):
pronto = False
while True:
valor1 = input(msg1)
if valor1.isnumeric():
pronto = True
else:
print('\033[1;31mERRO! FAVOR DIGITAR UM NÚMERO INTEIRO VÁLIDO\033[m')
if pronto:
break
return valor1
def linha(tamanho=42):
... |
valores = []
while True:
num = int(input('Digite um valor: '))
valores.append(num)
cont = str(input('Quer continuar? [S/N] ')).upper()
if cont == 'N':
break
print(f'Você digitou {len(valores)} elememtos.')
valores.sort(reverse=True)
print(f'Os valores em ordem decrescente são {valores}')
if 5 ... |
cont = 3
t1 = 0
t2 = 1
print('-----' * 12)
print('Sequência de Fibonacci')
print('-----' * 12)
valor = int(input('Quantos termos você quer mostrar ? '))
print('~~~~~' * 12)
print(f'{t1} ➙ {t2} ' , end='➙ ')
while cont <= valor:
t3 = t1 + t2
print(f' {t3}', end=' ➙ ')
t1 = t2
t2 = t3
t3 = t1
co... |
test = int(input())
while test > 0 :
n,k = map(int,input().split())
p = list(map(int,input().split()))
original = 0
later = 0
for i in p :
if i > k :
later += k
original += i
else :
later += i
original += i
print(orig... |
def main():
# Arithmetic operators
a = 7
b = 2
print(f'{a} + {b} = {a+b}')
print(f'{a} - {b} = {a-b}')
print(f'{a} * {b} = {a*b}')
print(f'{a} / {b} = {a/b}')
print(f'{a} // {b} = {a//b}')
print(f'{a} % {b} = {a%b}')
print(f'{a} ^ {b} = {a**b}')
# Bitwise ... |
class Employee:
#Initializaing
def __init__(self):
print('Employee created ')
#Deleting (Calling destructor)
def __del__(self):
print('Destructor called,Employee deleted')
obj=Employee()
del obj |
""" Hvad-specific exceptions
Part of hvad public API.
"""
__all__ = ('WrongManager', )
class WrongManager(Exception):
""" Raised when attempting to introspect translated fields from
shared models without going through hvad. The most likely cause
for this being accessing translated fields from
... |
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
result = [[1]]
for i in range(1, numRows):
temp = [1]
for j in range(1, i):
temp.append(result[-1][j-1] + result[-1][j])
temp.append(1)
result.append(temp... |
class responder():
def resp_hello():
hello=[]
hello.append('Hey there "{usr}"! how\'s it going?')
hello.append('Hi "{usr}" :grinning:')
hello.append('Hello "{usr}", whats up?')
hello.append('Hey "{usr}" :wave:,\nHow are you doing?')
hello.append('Hi "{usr}"!\nI\'m StrugBot, and I\'m super happy to be here!... |
"""Implement a weighted graph."""
class Graph(object):
"""Structure for values in a weighted graph."""
def __init__(self):
"""Create a graph with no values."""
self.graph = {}
def nodes(self):
"""Get all nodes in the graph to display in list form."""
return list(self.grap... |
class BaseCommand:
def __init__(self, table_name):
self.table_name = table_name
self._can_add = True
@staticmethod
def _convert_values(values):
converted = [SQLType.convert(v) for v in values]
return converted
def check_intersection(self, other):
return self.w... |
class Acl(object):
def __init__(self, read_acl):
self.read_acl = read_acl
@staticmethod
def from_acl_response(acl_response):
'''Takes JSON response from API and converts to ACL object'''
if 'read' in acl_response:
read_acl = AclType.from_acl_response(acl_response['read']... |
the_simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"]
print(the_simpsons[::-1])
for char in the_simpsons[::-1]:
print(f"{char} has a total of {len(char)} characters.")
print(reversed(the_simpsons))
print(type(reversed(the_simpsons))) # generator object
for char in reversed(the_simpsons): # laduje za kazda... |
TEST_CONFIG_OVERRIDE = {
# An envvar key for determining the project id to use. Change it
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
# build specific Cloud project. You can also use your own string
# to use your own Cloud project.
"gcloud_project_env": "BUILD_SPECIFIC_GCLOUD_... |
def test():
assert "for ent in doc.ents" in __solution__, "Itères-tu sur les entités ?"
assert x_pro.text == "X Pro", "Es-tu certain que x_pro contient les bons tokens ?"
__msg__.good(
"Parfait ! Bien sur, tu n'as pas besoin de faire cela manuellement à chaque fois."
"Dans le prochain exerc... |
# -*- coding: utf-8 -*-
"""
Defines constants used by P4P2P. Usually these are based upon concepts from
the Kademlia DHT and where possible naming is derived from the original
Kademlia paper as are the suggested default values.
"""
#: Represents the degree of parallelism in network calls.
ALPHA = 3
#: The maximum num... |
# grappelli
GRAPPELLI_ADMIN_TITLE = 'pangolin - Administration panel'
# rest framework
# REST_FRAMEWORK = {
# 'PAGINATE_BY_PARAM': 'limit',
# 'SEARCH_PARAM': 'q'
# }
|
"""
백준 19698번 : 헛간 청약
"""
N, W, H, L = map(int, input().split())
print(min(W//L * H//L, N)) |
x=input("Enter a umber of which you want to know the square root.")
x=int(x)
g=x/2
while (g*g-x)*(g*g-x)>0.00000000001:
g=(g+x/g)/2
print(g)
print(g)
|
'''
practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses
by Aashik J Krishnan/Aash Gates
'''
x = 10
y = "ten"
#step 1
x,y = y,x
#printing on next line
print(x)
print(y)
#end of the program |
idade = 18
carteiramotorista = True
print (idade >= 18 and carteiramotorista == True)
print ("Pode Dirigir")
velocidade = 90
radar = 100
radarfuncionando = False
print (velocidade > radar and radarfuncionando == True)
print ("Não foi multado")
velocidade1 = 101
print (velocidade1 >= radar) |
# coding: utf-8
SCHEMA_MAPPING = {
"persons": {
"type": "object",
"patternProperties": {
r"\d+": {
"type": "object",
"properties": {
"first_name": {"type": "string"},
"last_name": {"type": "string"},
... |
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return self.binary_search(nums, target, 0, len(nums) - 1)
def binary_search(self, nums, target, low, hight):
mid = low + (hight - low) // 2... |
# Single-quoted string is preceded and succeeded by newlines.
# Translators: This is a helpful comment.
_(
'5'
)
|
quarter=int(input())
p1=int(input())
p2=int(input())
p3=int(input())
time=0
while quarter>0:
if quarter == 0:
continue
p1+=1
quarter-=1
time+=1
if p1==35:
quarter+=30
p1=0
if quarter == 0:
continue
time+=1
p2+=1
quarter-=1
... |
"""
TAG: 0-1 Knapsack Problem, Dynamic Programming (DP), O(nW)
References:
- https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
weights and values of n items, capacity -> max value
"""
N, W = map(int, input().split()) # number of items, capacity
weights = []
values = []
for i in range(N):
w, v = m... |
# To print fibonacci series upto a given number n.
first = 0
second = 1
n = int(input())
print("Fibbonacci Series:")
for i in range(0,n):
print(first, end=", ")
next = second + first
first = second
second = next
|
nums = [0,1]
def calcFi():
n1 = nums[-2]
n2 = nums[-1]
sM = n1 + n2
phi = sM/n2
nums.append(sM)
return (phi)
for i in range(45):
if i % 15 == 0 or i == 44:
phi = calcFi()
print(phi)
if i == 44:
with open("outputs/phi.txt", "w") as f:
f... |
a = [2, 4, 5, 7, 8, 9]
sum = 0
for i in range(len(a) - 1):
if a[i] % 2 == 0:
sum = sum + a[i]
print(sum)
|
#students exams data entries for terminal report card
print("Westside Educational Complex--End Of second Terminal Report--Class-KKJA--Name:Theodora Obaa Yaa Gyarbeng")
while True:
student_score = float(input ("Enter the student score:"))
if student_score >= 1.0 and student_score <= 39.9:
print("stud... |
n = int(input())
l = []
c = 0
for i in range(0,n):
p = input()
print('c -> ', c)
if p in l:
c += 1
l.append(p)
print("Falta(m) {} pomekon(s).".format(151 - (n-c))) |
inst_25 = [(35,0,15),(29,0,20),(9,0,11),(9,13,35),(3,0,19),(37,0,8),(11,0,30),(19,0,25),(13,0,25),(39,0,18)]
inst_bait = [(10,0,10), (14,0,11), (33,0,26),(4,2,18),(4,20,30),(39,117,137),(12,5,21),(28,0,14),(32,5,14),(32,15,44),(36,0,9),(40,0,14),(2,1,15),(2,17,35),(5,160,168),(11,158,164),(13,116,131)]
inst_30 = []
... |
#To run the code, write
#from ishashad import ishashad
#then ishashad(number)
def ishashad(n):
if n % sum(map(int,str(n))) == 0:
print("True")
else:
print("False")
return |
class Relogio:
def __init__(self):
self.horas = 6
self.minutos = 0
self.dia = 1
def __str__(self):
return f"{self.horas:02d}:{self.minutos:02d} do dia {self.dia:02d}"
def avancaTempo(self, minutos):
self.minutos += minutos
while(self.minutos >= 60):... |
"""
@Author : xiaotao
@Email : 18773993654@163.com
@Lost modifid : 2020/4/24 10:02
@Filename : __init__.py.py
@Description :
@Software : PyCharm
""" |
# https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array-or-string/
# Time: O(n)
# Space: 1
def reverseByMiddles(arr):
n = len(arr)
limit = n//2
for i in range(limit):
temp = arr[i]
arr[i] = arr[(n-1)-i]
arr[(n-1)-i] = temp
return arr
arr = [1,2,3]
result = reverseByMiddles(arr)
print(r... |
coordinates_01EE00 = ((121, 126),
(121, 132), (121, 134), (121, 135), (121, 137), (121, 138), (121, 139), (121, 140), (121, 141), (122, 114), (122, 115), (122, 116), (122, 117), (122, 119), (122, 125), (122, 127), (122, 128), (122, 142), (123, 110), (123, 111), (123, 112), (123, 113), (123, 120), (123, 124), (123, 12... |
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars -drivers
cars_driven = drivers
carpool_carpacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available")
print("There are only", drivers, "drivers available")
prin... |
course = "Python Programming"
print(course.upper())
print(course.lower())
print(course.title())
course = " Python Programming"
print(course)
print(course.strip())
print(course.find("Pro"))
print(course.find("pro"))
print(course.replace("P", "-"))
print("Programming" in course)
print("Programming" not in course)
|
def init():
# Set locale environment
# Set config
# Set user and group
# init logger
pass |
def determinant(matA):
dimA = []
# find dimensions of arrA
a = matA
while type(a) == list:
dimA.append(len(a))
a = a[0]
#is it square
if dimA[0] != dimA[1]:
raise Exception("Matrix is not square")
#find determinant
total = 0
if dimA[0] == 2:
total = ma... |
#
# PySNMP MIB module BAY-STACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:19:06 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... |
objects = {}
def instantiate():
# This function is called once during server startup. Modify the global 'objects' dict with of instantiated
# shared objects that you wish to store in the parent process and have access to from child request handler
# processes. Each object must support being shared via... |
host = "localhost"
port = 9999
dboptions = {
"host": "194.67.198.163",
"user": "postgres",
"password": "werdwerd2012",
"database": "zno_bot",
'migrate': True
}
API_PATH = '/api/'
API_VERSION = 'v1'
API_URL = API_PATH + API_VERSION
|
class Frequency:
def __init__(self):
self.frequency = 0
def increment(self, i):
self.frequency = self.frequency + i
def decrement(self, i):
self.frequency = self.frequency - i
def __str__(self):
return str(self.frequency)
def __repr__(self):
return str(self.fr... |
print("---CONVERSÃO DE MEDIDAS---")
valor_metros = float(input("Informe o valor em metros à ser convertido: "))
valor_centimetros = valor_metros * 100
print("{} metros equivale a {} centimetros.".format(valor_metros, valor_centimetros)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.