content stringlengths 7 1.05M |
|---|
transactions_count = int(input('Enter number of transactions: '))
total = 0
while True:
if transactions_count <= 0:
break
transactions_cash = float(input('Enter transactions amount: '))
if transactions_cash >= 1:
total += transactions_cash
transactions_count -= 1
continue... |
class dotRebarSplice_t(object):
# no doc
BarPositions=None
Clearance=None
LapLength=None
ModelObject=None
Offset=None
Reinforcement1=None
Reinforcement2=None
Type=None
|
# coding: utf-8
MAX_INT = 2147483647
MIN_INT = -2147483648
class Solution(object):
def myAtoi(self, input_string):
"""
:type input_string: str
:rtype: int
"""
number = 0
sign = 1
i = 0
length = len(input_string)
while i < length and input_s... |
class Word:
"""
This class represents word as an object and has
feature extraction method that is used to build matrix for each word
based on most informative features by language experts
"""
def __init__(self, word):
self.word = word
@staticmethod
def extract_feat... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = l3 = ListNode(0)
while l1 and l2:
if l1.val > l2.val:
... |
'''https://leetcode.com/problems/remove-duplicates-from-sorted-array/'''
# class Solution:
# def removeDuplicates(self, nums: List[int]) -> int:
# l = len(nums)
# ans = 0
# for i in range(1, l):
# if nums[i]!=nums[ans]:
# ans+=1
# nums[i], nums[an... |
#!/usr/bin/env python3
def lst_intersection(lst1:list, lst2:list):
'''
Source: https://www.geeksforgeeks.org/python-intersection-two-lists/
'''
return [value for value in lst1 if value in set(lst2)]
def main():
return lst_intersection(lst1, lst2)
if __name__ == "__main__":
main()
|
__author__ = 'huanpc'
########################################################################################################################
HOST = "25.22.28.94"
PORT = 3307
USER = "root"
PASSWORD = "root"
DB = "opencart"
TABLE_ADDRESS = 'oc_address'
TABLE_CUSTOMER= 'oc_customer'
#####################################... |
def abort_if_false(ctx, param, value):
if not value:
ctx.abort()
|
HOST = "irc.twitch.tv"
PORT = 6667
OAUTH = "" # generate from http://www.twitchapps.com/tmi/
IDENT = "" # twitch account for which you used the oauth
CHANNEL = "" |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
capacity = 5000-A[0]
apples = sorted(A[1:])
sum = 0
total = 0
for idx,a in enumerate(apples):
if a+sum > capacity:
total = idx
... |
whole_clinit = [
'\n'
'.method static constructor <clinit>()V\n'
' .locals 1\n'
'\n'
' :try_start_0\n'
' const-string v0, "nc"\n'
'\n'
' invoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V\n'
' :try_end_0\n'
' .catch Ljava/lang/UnsatisfiedLi... |
class ValidBlockNetException(Exception):
pass
|
class Account:
all = []
def __init__(self, name:str, email: str, password: str):
self.name=name
self.email = email
self.password = password
Account.all.append(self)
def __repr__(self):
return f"{self.name}('{self.email}', '{self.password}')"
spotify =... |
'''
Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTim... |
# 12. put the string “avocado” in a variable and the string “radar” in another one
a='avocado'
r='radar'
# 13. print both strings in reverse
print(a[::-1])
print(r[::-1])
# 14. evaluate whether any of the two strings is palindrome (i.e. a string is palindrome if it can be read in the same way both from left to right an... |
# -*- coding:utf-8 -*-
"""
@author:SiriYang
@file: __init__.py
@time: 2019.12.24 20:33
"""
|
def as_div(form):
"""This formatter arranges label, widget, help text and error messages by
using divs. Apply to custom form classes, or use to monkey patch form
classes not under our direct control."""
# Yes, evil but the easiest way to set this property for all forms.
form.required_css_class = 'r... |
numbers = input('Enter a list of numbers (csv): ').replace(' ','').split(',')
numbers = [int(i) for i in numbers]
def sum_of_three(numbers):
summ = 0
for i in numbers:
summ += i
return summ
print('Sum:', sum_of_three(numbers)) |
{
"targets": [{
"target_name" : "test",
"defines": [ "V8_DEPRECATION_WARNINGS=1" ],
"sources" : [ "test.cpp" ],
"include_dirs": ["<!(node -e \"require('..')\")"]
}]
}
|
class QualifierList:
def __init__(self, qualifiers):
self.qualifiers = qualifiers
def insert_qualifier(self, qualifier):
self.qualifiers.insert(0, qualifier)
def __len__(self):
return len(self.qualifiers)
def __iter__(self):
return self.qualifiers
def __str__(se... |
st = input("enter the string")
upCount=0
lowCount=0
vowels=0
# for i in range (0,len(st)):
# print(st[i])
for i in range (0,len(st)):
# print(st[i])
if(st[i].isupper()):
upCount+=1
else:
lowCount+=1
for i in range(0,len(st)):
if(st[i]=='a') or (st[i]=='A') or (st[i]=='e') or (st[i]==... |
class Solution:
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
cnt, layer = 0, 0
for a, b in zip(S, S[1:]):
layer += (1 if a == '(' else -1)
if a + b == '()':
cnt += 2 ** (layer - 1)
return cnt |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Children, obj[6]: Education, obj[7]: Occupation, obj[8]: Income, obj[9]: Bar, obj[10]: Coffeehouse, obj[11]: Restaurant20to50, obj[12]: Direction_same, obj[13]: Distance
# {"feature": "Income", "instances": 34... |
# Bollinger Bands (BB)
"""
There are three bands when using Bollinger Bands
Middle Band – 20 Day Simple Moving Average
Upper Band – 20 Day Simple Moving Average + (Standard Deviation x 2)
Lower Band – 20 Day Simple Moving Average - (Standard Deviation x 2)
"""
def _bb_calc(ohlcv, period=20, number_of_std=2, ohlcv_s... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2013 ASMlover. 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... |
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
# Validate that incident name does not contain 'X'
if 'X' in incident.name:
helper.fail("The name must not contain 'X'.")
# Validate length of the incident name
if len(incident.name) > 100:
helper.fail("The name must be less than 100 characters.")
|
class VerifierError(Exception):
pass
class VerifierTranslatorError(Exception):
pass
__all__ = ["VerifierError", "VerifierTranslatorError"]
|
a = input()
a = int(a)
b = input()
set1 = set()
b.lower()
for x in b:
set1.add(x.lower())
if len(set1) == 26:
print("YES")
else:
print("NO")
|
"""
def elevator_distance(array):
return sum(abs(array[i+1] - array[i]) for i in range(len(array)-1))
"""
def elevator_distance(array):
d = 0
for i in range(0, len(array) -1):
d += abs(array[i] - array[i+1])
return d
|
# https://leetcode.com/problems/counting-bits/
#Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
class Solution(object):
def countBits(self, n):
"""
:type n: int
:rtype: List[int]
... |
#
# @lc app=leetcode id=125 lang=python3
#
# [125] Valid Palindrome
#
# https://leetcode.com/problems/valid-palindrome/description/
#
# algorithms
# Easy (30.28%)
# Total Accepted: 324.8K
# Total Submissions: 1.1M
# Testcase Example: '"A man, a plan, a canal: Panama"'
#
# Given a string, determine if it is a palind... |
vfx = None
##
# Init midi module
#
# @param: vfx object
# @return: void
##
def init(vfx_obj):
global vfx
vfx = vfx_obj
def debug():
global vfx
if(vfx.usb_midi_connected == False):
print('Midi not connected')
pass
print("Midi trig: %s | id: %s | name: %s |active ch: %s | midi new... |
"""Preset GridWorlds module
Are used by the :obj:`~smartexploration.environments.gridworld.GridWorld` to
generate the gridworld.
"""
def easy():
"""Easy GridWorld
Returns
-------
:obj:`str`
name
double :obj:`list` of `int`
layout
:obj:`int`
scale
"""
name = "E... |
def mail_send(to, subject, content):
print(to)
print(subject)
print(content)
|
# https://leetcode-cn.com/problems/permutation-sequence/solution/
# 第K个排列
class Solution(object):
def dfs(self, nums, length, depth, path, used, ans):
if length == depth:
return path
# 当前层的排列数
cur = self.factorial(length - depth - 1)
for i in range(0, length):
... |
SAFE_METHODS = ("GET", "HEAD", "OPTIONS")
class BasePermission(object):
"""
A base class from which all permission classes should inherit.
"""
def has_permission(self, request, view):
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True
d... |
a = 1
b = 0
c = 0
i = 0
while True:
c = a + b
b = a
a = c
if i % 100000 == 0:
print(c)
i += 1
|
def create_sensorinfo_file(directory):
pass
def create_metadata_file(directory):
pass
def create_delivery_note_file(directory):
pass
def create_data_delivery(directory):
pass
|
class Plugin_OBJ():
def __init__(self, plugin_utils):
self.plugin_utils = plugin_utils
self.channels_json_url = "https://iptv-org.github.io/iptv/channels.json"
self.filter_dict = {}
self.setup_filters()
self.unfiltered_chan_json = None
self.filtered_chan_json = ... |
nome = 'Cristiano'
sobrenome = 'Cunha'
nome_completo = f'{nome} {sobrenome}'
idade = 22
print(f'Nome: {nome_completo} - Idade: {idade}')
print(type(idade))
#Tudo no python são objetos |
# Chicago 106 problem
# try https://e-maxx.ru/algo/levit_algorithm
places, streets = list(map(int, input().split()))
graph = dict()
# dynamic = [-1 for i in range(places)]
for i in range(streets):
start, end, prob = list(map(int, input().split()))
if start not in graph:
graph[start] = list()
if end... |
line = input()
while line != "0 0 0 0":
line = list(map(int, line.split()))
starting = line[0]
for i in range(4):
line[i] = ((line[i] + 40 - starting) % 40) * 9
res = 360 * 3 + (360 - line[1]) % 360 + (360 + line[2] - line[1]) % 360 + (360 + line[2] - line[3]) % 360
print(res)
line ... |
dia = input('Qual o dia do seu anivesario? ')
mes = input('Qual o mes do seu aniversario? ')
ano = input('Qual o ano do seu aniversario? ')
print('Você nasceu dia', dia,'de',mes,'de',ano,', Correto?')
|
#
# PySNMP MIB module CISCO-DOT11-WIDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DOT11-WIDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:55:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
SETTING_SERVER_CLOCK = "RAZBERRY_CLOCK"
SETTING_SERVER_TIME = "RAZBERRY_TIME"
SETTING_LAST_UPDATE = "LAST_UPDATED"
SETTING_SERVER_ADDRRESS = "RAZBERRY_SERVER"
SETTING_SERVICE_TIMEOUT = "SERVICE_TIMEOUT" |
# Example 1
i = 0
while i <= 10:
print(i)
i += 1
# Example 2
available_fruits = ["Apple", "Pearl", "Banana", "Grapes"]
chosen_fruit = ''
print("We have the following available fruits: Apple, Pearl, Banana, Grapes")
while chosen_fruit not in available_fruits:
chosen_fruit = input("Please choose one of the ... |
class PaymentError(Exception):
pass
class MpesaError(PaymentError):
pass
class InvalidTransactionAmount(MpesaError):
pass
|
def balancedStringSplit(self, s: str) -> int:
l, r = 0, 0
c = 0
for i in range(len(s)):
if s[i] == "L":
l += 1
if s[i] == "R":
r+=1
if l == r:
c+=1
return c |
def fail():
raise Exception("Ooops")
def main():
fail()
print("We will never reach here")
try:
main()
except Exception as exc:
print("Some kind of exception happened")
print(exc)
|
PREPROD_ENV = 'UAT'
PROD_ENV = 'PROD'
PREPROD_URL = "https://mercury-uat.phonepe.com"
PROD_URL = "https://mercury.phonepe.com"
URLS = {PREPROD_ENV:PREPROD_URL,PROD_ENV:PROD_URL} |
"""\
Bunch.py: Generic collection that can be accessed as a class. This can
be easily overrided and used as container for a variety of objects.
This program is part of the PyQuante quantum chemistry program suite
Copyright (c) 2004, Richard P. Muller. All Rights Reserved.
PyQuante version 1.2 and later is cov... |
class FanHealthStatus(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_fan_health_status(idx_name)
class FanHealthStatusColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_fans()
|
# Time: O(26 * n)
# Space: O(26 * n)
class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
self.size = [1]*n
self.total = n
def find_set(self, x):
stk = []
while self.set[x] != x: # path com... |
__all__ = ['authorize',
'config',
'interactive',
'process']
|
XM_OFF = 649.900675
YM_OFF = -25400.296854
ZM_OFF = 15786.311942
MM_00 = 0.990902
MM_01 = 0.006561
MM_02 = 0.006433
MM_10 = 0.006561
MM_11 = 0.978122
MM_12 = 0.006076
MM_20 = 0.006433
MM_21 = 0.006076
MM_22 = 0.914589
XA_OFF = 0.141424
YA_OFF = 0.380157
ZA_OFF = -0.192037
AC_00 = 100.154822
AC_01 = 0.327... |
# The mathematical modulo is used to calculate the remainder of the
# integer division. As an example, 102%25 is 2.
# Write a function that takes two values as parameters and returns
# the calculation of a modulo from the two values.
def mathematical_modulo(a, b):
''' divide a by b, return the remainder '''
re... |
class CohereError(Exception):
def __init__(
self,
message=None,
http_status=None,
headers=None,
) -> None:
super(CohereError, self).__init__(message)
self.message = message
self.http_status = http_status
self.headers = headers or {}
def __str... |
"""
:testcase_name record_metrics
:author Sriteja Kummita
:script_type class
:description Metrics contains the getters and setter for precision and recall. RecordMetrics uses these methods
to set and get the respective metrics.
"""
class Metrics:
def __init__(self):
self.precision = 0.0
self.recal... |
"""
Default termsets for various languages
"""
# portuguese termset dictionary
pt = dict()
pseudo = [
'não mais',
'não é capaz de ser',
'não está certo se',
'não necessariamente',
'sem mais',
'sem dificuldade',
'talvez não',
'não só',
'sem aumento',
'sem alterações significativas',
'sem alterações',
'sem alterações ... |
#
# PySNMP MIB module WWP-LEOS-PORT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-PORT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:38:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
'''Reescreva a função leiaInt() que fizemos no desafio 104, incluindo agora a possibilidade da digitação
de um número de tipo inválido. Aproveite e crie também uma função leiaFloat() com a mesma funcionalidade.'''
def leiaint(msg):
while True:
try:
n=int(input(msg))
except(ValueError,Typ... |
budget = int(input())
season = input()
fisherman = int(input())
rent_price = 0
if season == "Spring":
rent_price = 3000
elif season == "Summer" or season == "Autumn":
rent_price = 4200
elif season == "Winter":
rent_price = 2600
if fisherman <= 6:
rent_price = rent_price - (rent_price * 0.1)
elif 7 <= ... |
def pascal_triangle(n):
if n == 0:
return [1]
else:
row = [1]
line_behind = pascal_triangle(n - 1)
for r in range(len(line_behind) - 1):
row.append(line_behind[r] + line_behind[r + 1])
row += [1]
return row
print(pascal_triangle(4))
|
class YesError(Exception):
pass
class YesUserCanceledError(YesError):
pass
class YesUnknownIssuerError(YesError):
pass
class YesAccountSelectionRequested(YesError):
redirect_uri: str
class YesOAuthError(YesError):
oauth_error: str
oauth_error_description: str
|
class Packtry(object):
@staticmethod
def print():
print('print')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class UnsupportedFileFormatError(Exception):
"""
This exception is intended to communicate that the file extension is not one of
the supported file types and cannot be parsed with AICSImage.
"""
def __init__(self, data, **kwargs):
super().__in... |
class Constants:
APPLICATION_TITLE = "Welcome to Kafka Local Setup Tool"
APPLICATION_WINDOW_TITLE = "Kafka Application Tool"
START_BUTTON = "Start"
STOP_BUTTON = "Stop"
CHOOSE_FOLDER = "Choose Folder"
SELECT_FOLDER = "Select the folder"
ZOOKEEPER_START_SERVER_PATH = "bin/zookeeper-server-sta... |
class User():
def __init__(self, Name, LastName, ID, Mail, Phone):
self.Name = Name
self.LastName = LastName
self.ID = ID
self.Mail = Mail
self.Phone = Phone
def Describe_U(self):
s = "\nName: " + self.Name + " "+self.LastName + "\nID: "+self.ID
... |
with open("data_100.vrt", "rb") as f_in:
with open("data_broken_header.vrt", "wb") as f_out:
f_out.write(f_in.read(2))
with open("data_missing_fields.vrt", "wb") as f_out:
f_out.write(f_in.read(4))
with open("data_broken_fields.vrt", "wb") as f_out:
f_out.write(f_in.read(6))
with... |
"""
Euclidean common divisor algorithm.
"""
def greatest_common_divisor(num_a: int, num_b: int) -> int:
"""
A method to compute the greatest common divisor.
Args:
num_a (int): The first number.
num_b (int): Second number
Returns:
The greatest common divisor.
"""
... |
n = int(input())
arr = [int(x) for x in input().split()]
if all(item < 0 for item in arr):
print(0)
else:
mx = 0
su = 0
for item in arr:
su += item
if su < 0:
su = 0
if su > mx:
mx = su
print(mx)
|
def flatten_list(mylist,index=0,newlist=[]):
if(index==len(mylist)):
return newlist
if(type(mylist[index])== list):
newlist.extend(flatten_list(mylist[index],0,[]))
else:
newlist.append(mylist[index])
return flatten_list(mylist,index+1,newlist)
mylist=[1,2,[3,4],[5,[6,7,... |
# !/usr/bin/env python
# -*-coding:utf-8 -*-
# Warning :The Hard Way Is Easier
"""
现在IPV4下用一个32位无符号整数来表示,
一般用点分方式来显示,点将IP地址分成4个部分,
每个部分为8位,表示成一个无符号整数(因此不需要用正号出现),
如10.137.17.1,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。
现在需要你用程序来判断IP是否合法。
# 核心: 判断每个部分数值是否小于255
"""
def Solution(s: str):
l = [int(i) for i in s.... |
class Service(object):
'''Basic service interface.
If you want your own service, you should respect this interface
so that your service can be used by the looper.
'''
def __init__(self, cfg, comp, outdir):
'''
cfg: framework.config.Service object containing whatever parameters
... |
# Copyright 2015 Curtis Sand
#
# 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, ... |
def shorten_string(string : str, max_length : int):
shortened_name = string
if len(string) > max_length:
shortened_name = string[0:max_length] + '...'
return shortened_name |
#!/usr/bin/env python3
#
# Prints to stdout very fast.
#
# Optimal time:
# time ./stress.py >/dev/null
# Actual time:
# time ./stress.py
for i in range(1000000):
print('\033[31;1m', i, '\033[0m')
|
GstreamerPackage ('gstreamer', 'gst-plugins-bad', '0.10.23', configure_flags = [
' --disable-gtk-doc',
' --with-plugins=quicktime',
' --disable-apexsink',
' --disable-bz2',
' --disable-metadata',
' --disable-oss4',
' --disable-theoradec'
])
|
n = int(input())
list_names = []
for i in range(n):
name = input()
list_names.append(name)
print(list_names) |
class CubeOrder:
"""""
There does not seem to be one single standard for cube representation among various solvers.
Different programs will receive an input string expecting a different order.
This class allows us to convert from one order to another order allowing stitching among solvers.
... |
class Dataset(object):
"""
Class representation of a dataset on Citrination.
"""
def __init__(self, id, name=None, description=None,
created_at=None):
"""
Constructor.
:param id: The ID of the dataset (required for instantiation)
:type id: int
:param... |
"""Exception types."""
class IntegratorError(RuntimeError):
"""Error raised when integrator step fails."""
class NonReversibleStepError(IntegratorError):
"""Error raised when integrator step fails reversibility check."""
class ConvergenceError(IntegratorError):
"""Error raised when solver fails to con... |
class Solution:
# 1st two-pass solution
# O(2n) time | O(1) space
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero = 0
for i in range(len(nums)):
if nums[i] == 0:
nums[i], num... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
EXPECTED_REPR = u""""""
EXPECTED_AGG_QUERY = {
"week": {
"aggs": {
"nested_below_week": {
"aggs": {
"local_metrics.field_class.name": {
"aggs": {
"min_f1_score... |
"""Py4research main library. Note that it consists
of two modules.
"""
__version__ = '1.0.1'
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class DbTypeEnum(object):
"""Implementation of the 'DbType' enum.
Specifies the type of the database in Oracle Protection Source.
'kRACDatabase' indicates the database is a RAC DB.
'kSingleInstance' indicates that the database is single instance.... |
# -*- coding: utf-8 -*-
textFile = """
.
.
.
One has to consider that the database is closed.
Spyder
"""
print("Osman Orhun OZSAN")
print("2017-01-19 14:00:00")
print(textFile)
|
def mergeSort(myArray):
# print to show splitting
print("Splitting ",myArray)
# if array is greater than 1 then:
if len(myArray) > 1:
# mid, leftside, and right side of array stored as variables
mid = len(myArray)//2
lefthalf = myArray[:mid]
righthalf = myArray[m... |
class TSheetsError(Exception):
"""Exception Class to handle the failure of the request."""
def __init__(self, base_exception=None):
self.base_exception = base_exception
def __str__(self):
if self.base_exception:
return str(self.base_exception)
return "An unknown error... |
"""Compatibility support for Python 2 and 3."""
try:
string_types = (basestring,)
except NameError:
string_types = (str,)
|
""" Faça um programa que leia três números e mostre qual é o MAIOR
e qual o MENOR."""
num1 = int(input("Digite o primeiro número:"))
num2 = int(input('Digite o segundo número:'))
num3 = int(input('Digite o terceiro número:'))
if num1 > num2 and num1 > num3:
maior = num1
else:
if num2 > num3:
maior = nu... |
ATOM, BOND, DIGIT, LPAR, RPAR, LSPAR, RSPAR, PLUS, MINUS, DOT, WILDCARD, PERCENT, AT, COLON, EOF = (
'ATOM', 'BOND', 'DIGIT', '(', ')', '[', ']', '+', '-', '.', '*', '%', '@', ':', 'EOF'
)
SYMBOLS_TR = {
'=': BOND,
'#': BOND,
'$': BOND,
'/': BOND,
'\\': BOND,
'(': LPAR,
')': RPAR,
'... |
#!/usr/bin/env python3
class Flower():
color = 'unknown'
rose = Flower()
rose.color = "red"
violet = Flower()
violet.color = "blue"
this_pun_is_for_you = "The honey is sweet and so are you"
print("Roses are {},".format(rose.color))
print("violets are {},".format(violet.color))
print(this_pun_is_for_you)
|
def query(start, end):
if start < end:
print('M {} {}'.format(start, end), flush=True)
else:
print('M {} {}'.format(end, start), flush=True)
def swap(pos1, pos2):
if pos1 < pos2:
print('S {} {}'.format(pos1, pos2), flush=True)
else:
print('S {} {}'.format(pos2, pos1), fl... |
# -*- mode: python -*-
DOCUMENTATION = '''
---
module: group_by
short_description: Create Ansible groups based on facts
description:
- Use facts to create ad-hoc groups that can be used later in a playbook.
version_added: "0.9"
options:
key:
description:
- The variables whose values will be used as groups
... |
"""
10.2.1
Can you implement the dynamic-set operation INSERT on a singly linked list in O(1) time? How about DELETE?
"""
class Node:
def __init__(self, data=0, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
"""Insertion at t... |
array = [3, 2, 1]
index = 1 # 0: first item, 1: second item...
item = 100
print(array) # [3, 2, 1]
array = array[0:index] + [item] + array[index:] # ≡
print(array) # [3, 100, 2, 1] |
#!/usr/bin/env python3
"""Advent of Code 2021 Day 12 - Passage Pathing"""
with open('inputs/day_12.txt', 'r') as aoc_input:
lines = [line.strip().split('-') for line in aoc_input.readlines()]
connections = {}
for line in lines:
from_cave, to_cave = line
if from_cave not in connections.keys():
co... |
#class that represents a resource
class Resource:
def __init__(self,name,id):
self.name = name
self.ID = id
self.aliases = [name]
#list of all the events this resource is involved in
#reflects when the resource worked on which object
#list of Event objects
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.