content stringlengths 7 1.05M |
|---|
''' Merge sort of singly linked list
Merge sort is often prefered for sorting a linked list. The slow random access performance
of linked list make other algorithms such as quicksort perform poorly and others such as
heapsort completely impossible.
'''
#Code
class Node:
def __init__(self,data):
... |
# regular if/else statement
a = 10
if a > 5:
print('a > 5')
else:
print('a <= 5')
# if/elif/else
a = 3
if a > 5:
print('a > 5')
elif a > 0:
print('a > 0')
else:
print('a <= 0')
# assignment with if/else - ternary statement
b = 'a is positive' if a >= 0 else 'a is negative'
print(b)
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
node = head
shead = None
dummy = ListNode(0, head)
while node:
... |
#import wx
Q3_IMPL_QT="ui.pyqt5"
Q3_IMPL_WX="ui.wx"
#Q3_IMPL="wx"
#default impl
#global Q3_IMPL
Q3_IMPL=Q3_IMPL_QT
Q3_IMPL_SIM='sim.default'
#from wx import ID_EXIT
#from wx import ID_ABOUT
ID_EXIT = 1
ID_ABOUT = 2
MAX_PINS = 256
MAX_INPUTS = 256
MAX_OUTPUTS = 256
MAX_DYNAMICS = 256
MAX_SIGNAL_SIZE = 64
|
# lec11prob5.py
#
# Lecture 11 - Classes
# Problem 5
#
# edX MITx 6.00.1x
# Introduction to Computer Science and Programming Using Python
'''
Consider the following code from the last lecture video.
Your task is to define the following two methods for the intSet class:
1. Define an intersect method that returns a... |
print('-=-' * 10, '\nEmpréstimo Garantido!!!')
print('-=-' * 10)
valor = float(input('Qual o valor da casa: R$'))
sal = float(input('Qual seu salário? R$'))
anos = int(input('Pretende pagar em quantos anos? '))
meses = anos * 12
prest = valor / meses
if prest > (sal*0.30):
print('Empréstimo não autorizado as presta... |
# This test is here so we don't get a non-zero code from Pytest in Travis CI build.
def test_dummy():
assert 5 == 5
|
# 矩形覆盖
class Solution:
def rectCover(self, number):
# write code here
if number == 0:
return 0
if number == 1:
return 1
if number == 2:
return 2
a = 1
b = 2
for i in range(3, number + 1):
b = a + b
a... |
__metaclass__ = type
#classes inherting from _UIBase are expected to also inherit UIBase separately.
class _UIBase(object):
id_gen = 0
def __init__(self):
#protocol
self._content_id = _UIBase.id_gen
_UIBase.id_gen += 1
def _copy_values_deep(self, other):
pass
def _clone... |
#https://www.codewars.com/kata/the-office-ii-boredom-score
"""Every now and then people in the office moves teams or departments.
Depending what people are doing with their time they can become more or less boring. Time to assess the current team.
You will be provided with an object(staff) containing the staff names a... |
"""Docstring.
Details
"""
__all__ = ('InvalidParameterError')
class InvalidParameterError(Exception):
"""A specific exception for invalid parameter."""
def __init__(self, message): # pylint:disable=W0235
"""Init function."""
super().__init__(message)
|
"""
고객들이 원하는 토핑을 골라 주문할 수 있는 피자집의 주문 시스템을 만든다고 하자.
이 피자집에는 0부터 19까지의 번호를 갖는 스무가지의 토핑이 있으며, 주문시 토핑을 넣기/ 넣지 않기를 선택할 수 있다.
그러면 한 피자의 정보는 스무 종류의 원소만을 갖는 집합이 되고, 비트마스크를 이용해 표현할 수 있다.
"""
# 비트마스크를 이용하는 집합에서 공집합을 표현하는것은 너무나 간단하다. -> 0
# 꽉 찬 집합을 표현하는 것 1 << 20 - 1이 된다.
# 집합의 가장 기초적인 연산은 원소를 추가하고 삭제하는 것이다. 비트마스크를 사용한 집합에서 원소를 ... |
#!/usr/bin/env python3
class Node(object):
def __init__(self, ip, port):
self.ip = ip
self.port=port
self.name="Node: %s:%d" % (ip, port)
def __name__(self):
return self.name
def start(self):
return
def stop(self):
return
|
description = 'PANDA Heusler-analyzer'
group = 'lowlevel'
includes = ['monofoci', 'monoturm', 'panda_mtt']
extended = dict(dynamic_loaded = True)
devices = dict(
ana_heusler = device('nicos.devices.tas.Monochromator',
description = 'PANDA\'s Heusler ana',
unit = 'A-1',
theta = 'ath',
... |
#!/usr/bin/env python
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of t... |
# -*- coding: utf-8 -*-
def test_cookies_group(testdir):
result = testdir.runpytest(
'--help',
)
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines([
'cookies:',
'*--template=TEMPLATE*',
])
|
class TestFixupsToPywb:
# Test random fixups we've made to improve `pywb` behavior
def test_we_do_not_try_and_rewrite_rel_manifest(self, proxied_content):
# The '_id' here means a transparent rewrite, and no insertion of
# wombat stuff
assert (
'<link rel="manifest" href="/p... |
def transpose(the_array):
ret = map(list, zip(*the_array))
ret = list(ret)
return ret
def get_unique_list(dict_list, key="id"):
# https://stackoverflow.com/questions/10024646/how-to-get-list-of-objects-with-unique-attribute
seen = set()
return [seen.add(d[key]) or d for d in dict_list if d a... |
####################################################
# package version -- named "pkgdir.testapi"
# this function is loaded and run by testapi.c;
# change this file between calls: auto-reload mode
# gets the new version each time 'func' is called;
# for the test, the last line was changed to:
# return x + y... |
"""Author @Sowjanya"""
"""Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target."""
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashMap = {}
for i,n in enumerate(nums):
if (target-n) in... |
def part1(input) -> int:
count1 = count3 = 0
for i in range(len(input) - 1):
if input[i+1] - input[i] == 1:
count1 += 1
elif input[i+1] - input[i] == 3:
count3 += 1
return count1 * count3
def part2(input) -> int:
valid = {}
def possibleArrangements(input) -> ... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Function: formatted text document by adding newline
# Author: king
def main():
print('This python script help you formatted text document.')
fin = input('Input the file location : ')
fout = input('Input the new file location: ')
print('begin...')
MAX_SI... |
s=0
i=0
v=0
while v>=0:
v = float(input("digite o valor da idade: "))
if v>=0:
s = s+v
print(s)
i = i+1
print(i)
r = s/(i)
print(r)
print(r)
|
numeros = {
'william': 16,
'igor': 5,
'milly': 7,
'iago': 10,
'kelly': 25,
}
for nome, num in numeros.items():
print(f'O número favorito de {nome.title()} é {num}.')
|
__author__ = 'zz'
class BaseVerifier:
def verify(self, value):
raise NotImplementedError
class IntVerifier(BaseVerifier):
def __index__(self, upper, bot):
self.upper = upper
self.bot = bot
def verify(self, value):
if isinstance(value, int):
return False
... |
#
# LeetCode
# Algorithm 141 Linked List Cycle
#
# Rick Lan, May 6, 2017.
# See LICENSE
#
# Your runtime beats 69.76 % of python submissions.
#
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} m
# @param {integer} n
# @return {ListNode}
def reverseBetween(self, head, m, n):
dumpy = ListNode(0)
... |
class Solution:
def twoSum(self, nums, target: int):
d = {}
for i in range(len(nums)):
j = target - nums[i]
if j in d:
return [d[j], i]
else:
d[nums[i]] = i
s = Solution()
print(s.twoSum(
[3, 2, 4], 6))
|
n = float(input('Digite o 1º numero: '))
n1 = float(input('Digite o 2º numero: '))
n2 = 0
while n2 != 5:
print(''' [1] somar
[2] Multiplicar
[3] Maior
[4] Novos numeros
[5] Sair do programa''')
n2 = int(input('Sua opção: '))
if n2 == 1:
n3 = n + n1
print(f'A soma entre {n} + {n1} é ... |
""" Addoperation class """
class AddOperation:
""" Class for add operation """
def __init__(self, num1, num2):
""" Init function """
self.num1 = num1
self.num2 = num2
self.result = 0
def process(self):
""" Process function to perform operation"""
self.resu... |
def tri_bulle(L):
pointer = 0
while pointer < len(L):
left = 0
right = 1
while right < len(L) - pointer:
if L[right] < L[left]:
L[left], L[right] = L[right], L[left]
left += 1
right += 1
pointer += 1
return L
print(tri_bulle([8, -1, 2, 5, 3, -2])) |
"""
Brightness
"""
class Brightness(object):
"""
Brightness facade
"""
def current_level(self):
return self._current_level()
def set_level(self, level):
return self._set_level(level)
# private
def _current_level(self):
raise NotImplementedError()
def _set_le... |
def maximo(a, b):
""" Função que retorna o valor máximo entre dois parâmetros.
>>> maximo(3, 4)
4
>>> maximo(0, -1)
0
:param a: number
:param b: number
:return: number
"""
if a > b:
return a
else:
return b
|
t = int(input())
for case in range(t):
s = input()
numbers = '0123456789'
if (s[0] == 'R' and (s[1] in numbers) and ('C' in s)):
iC = 0
for i in range(len(s)):
if (s[i] == 'C'):
iC = i
break
row = s[1:iC]
col = int(s[iC +... |
#
# PySNMP MIB module STACK-TOP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STACK-TOP
# Produced by pysmi-0.3.4 at Wed May 1 15:10:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... |
class Solution:
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
if len(candies) == 0 or len(candies)%2 !=0:
return 0
h = set()
for i in candies:
h.add(i)
l=len(candies)/2
if(len(h)>l):
... |
all_bps = """BFBBBBBLLR
BBFFBBFRRL
FBFBFFFRRL
BBFFFBFRRL
BFFBFBFRLL
FFBBBFBLRL
BFFFBFFLLR
FBFFFFBLRR
FBFFBBBRRR
BFFBFFFLLR
BFFFFFBLLL
FFBBFFBLRR
BFFFFFBRLR
FBFBFBFLLL
FFBFBFFLLL
BBFFFFFLLL
FFFBBBFLLL
BBFFBFBLLR
FFBFBFBRRR
BFFBFFFRRR
BBFFBFBRLR
FFFBFBFLRL
BBFFBBBLRR
FBBFFFFLLR
BBBFBBFLLL
BFFFFBBRLL
FBBFBFBRRL
FFBBBFFRRR... |
def Setup(Settings,DefaultModel):
# set1-test_of_models_against_datasets/models_30m_640px.py
Settings["experiment_name"] = "set1c_Models_Test_30m_640px"
Settings["graph_histories"] = ['together', [0,1], [1,2], [0,2]]
n=0
# 5556x_minlen30_640px 5556x_minlen20_640px 5556x_reslen20_299px 5556x_resle... |
#!/usr/bin/env python3
DEV = "/dev/input/event19"
CONTROLS = {
144: [
"SELECT",
"START",
"CROSS",
"CIRCLE",
"SQUARE",
"TRIANGLE",
"UP",
"RIGHT",
"DOWN",
"LEFT",
],
96: [
"CENTER",
]
}
def trial(n: int) -> None:
for size in CONTROLS.keys():
for control in CONTROLS[size]:
print(f"PRE... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# class Solution(object):
# def swapPairs(self, head):
# """
# :type head: ListNode
# :rtype: ListNode
# """
class Solution(objec... |
# Demo Python Functions - Keyword Arguments
'''
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
'''
# Example:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = ... |
N, L = input().split()
N = int(N)
L = int(L)
#print(N, L)
s_list = input().split()
citations = [ int(s) for s in s_list]
def findHIndex(citations):
citations.sort(reverse=True)
N = len(citations)
res = N
for i in range(N):
if citations[i]<i+1:
res = i
break
retu... |
#######################################
## ADD SOME COLOR
# pinched and tweaked from https://github.com/impshum/Multi-Quote/blob/master/run.py
class color:
white, cyan, blue, red, green, yellow, magenta, black, gray, bold = '\033[0m', '\033[96m','\033[94m', '\033[91m','\033[92m','\033[93m','\033[95m', '\033[30m', '\0... |
# -*-coding: utf-8 -
# 매도호가 정보의 경우 동시호가 시간에도 올라오므로 주의
AUTO_TRADING_OPERATION_TIME = [[[9, 0], [15, 19]]]
# 조건검색식 적용시간
CONDITION_INFO = {
"장초반": {
"start_time": {
"hour": 8,
"minute": 5,
"second": 0,
},
"end_time": {
"hour": 15,
"... |
def lex_lambda_handler(event, context):
intent_name = event['currentIntent']['name']
parameters = event['currentIntent']['slots']
attributes = event['sessionAttributes'] if event['sessionAttributes'] is not None else {}
response = init_contact(intent_name, parameters, attributes)
return response
... |
# Copyright (C) 2018 Henrique Pereira Coutada Miranda
# All rights reserved.
#
# This file is part of yambopy
#
#
"""
submodule with classes to read BSE optical absorption spectra claculations
and information about the excitonic states
"""
|
BLACK = (0, 0, 0)
GREY = (142, 142, 142)
RED = (200, 72, 72)
ORANGE = (198, 108, 58)
BROWN = (180, 122, 48)
YELLOW = (162, 162, 42)
GREEN = (72, 160, 72)
BLUE = (66, 72, 200)
|
#!/usr/bin/env python
def square_gen(is_true):
i = 0
while True:
yield i**2
i += 1
g = square_gen(False)
print(next(g))
print(next(g))
print(next(g))
|
class A:
def __bool__(self):
print('__bool__')
return True
def __len__(self):
print('__len__')
return 1
class B:
def __len__(self):
print('__len__')
return 0
print(bool(A()))
print(len(A()))
print(bool(B()))
print(len(B()))
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
c = 0
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
global c
return_head = head
prev = ListNode(0)
prev.next = return_head
... |
d1 = {1:'Sugandh', 2:'Divya', 3:'Mintoo'}
print("deleting a key from the dictionary...")
del d1[3]
print(d1)
print("deleting the same key again...")
del d1[3]
print(d1)
|
class ObtenedorDeEntrada:
def getEntrada(self):
f = open ('Entrada.txt','r')
entrada = f.read()
print(entrada)
f.close()
return entrada
#input("Introduce el texto\n") |
{
"name": "train-nn",
"s3_path": "s3://tht-spark/executables/SDG_Data_Technologies_Model.py",
"executors": 2,
}
|
# parameters of the system
# data files
temp = np.load('./data/temp_norm.npy')
y = np.load('./data/total_load_norm.npy')
load_meters = np.load('./data/load_meters_norm.npy')
# system parameters
T, num_meters = load_meters.shape
num_samples = T
# training parameters
hist_samples = 24
train_samples = int(0.8 * num_... |
datas = {
'style' : 'sys',
'parent' :'boost',
'prefix' :['boost','simd'],
}
|
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
buy = math.inf
for price in prices:
if price < buy:
buy = price
elif (p := price - buy) > profit:
profit = p
return profit
|
def maior_elemento(lista):
elemento_ref = lista[0]
maior_elemento = 0
for i in lista:
if i >= elemento_ref:
maior_elemento = i
return maior_elemento |
#!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# 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.... |
pjs_setting = {"hyperopt" :{"AGENT_TYPE":'"randomwalk"', "CIRCLE_TYPE":'"line"', "min_n_circle":1000, "max_n_circle":4000},
"gaopt" :{"AGENT_TYPE":'"ga"', "CIRCLE_TYPE":'"normal_sw"', "min_n_circle":500, "max_n_circle":3000},
"bayesopt" :{"AGENT_TYPE":'"randomwalk"', "CIRCLE_TYPE... |
# 28. Implement strStr()
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
"""
Return the index of the first occurrence of needle in haystack,
or -1 if needle is not part of haystack.
"""
if not len(needle):
return 0
s = needle + '$' +... |
for c in range(1, 10):
print(c)
print('FIM')
w = 1
while w < 10:
print(w)
w = w +1
print('FIM')
for i in range(1, 5):
n = int(input('Digite um número: '))
print('FIM')
num = 1
while num != 0:
num = int(input('Digite um número: '))
print('FIM')
r = 'S'
while r == 'S':
number = int(input('Digi... |
#!/usr/bin/python
#coding=utf-8
# 稳定排序,算法时间复杂度O(n^2)
arr = [1,3,4,2,8,0,3,6,14,9]
def sort(arr):
current = None
for i in range(len(arr)-1):
current = arr[ i+1 ]
preIndex = i
while ( preIndex >= 0 and current < arr[preIndex] ):
arr[preIndex+1] = arr[preIndex]
... |
__version__ = "11.0.2-2022.02.08"
if __name__ == "__main__":
print(__version__)
|
array = [3,5,-4,8,11,1,-1,6]
targetSum = 10
# def twoNumberSum(array, targetSum):
# # Write your code here.
# arrayOut = []
# for num1 in array:
# for num2 in array:
# if (num1+num2==targetSum) and (num1 != num2):
# arrayOut.append(num1)
# arrayOut.append... |
class Annotation:
def __init__(self, val, min_y, max_y, min_x, max_x):
self.val = val
self.min_y = min_y
self.max_y = max_y
self.min_x = min_x
self.max_x = max_x
class Bitmap:
def __init__(self, min_y, max_y, min_x, max_x):
self.min_y = min_y
self.max_y ... |
# Print multiplication tables
# 1 2 3 4 .. 10
# 2 4 6 8 20
# 3 6 9 12 30
# .. .. .. .. ..
for i in range(1, 11):
for j in range(1, 11):
print(str(j * i) + '\t', end='')
pri... |
# --------------
##File path for the file
file_path
#Code starts here
def read_file(path):
file=open(file_path,'r')
sentence=file.readline()
file.close()
return sentence
sample_message=read_file(file_path)
# --------------
#Code starts here
file_path_1,file_path_2
message_1=read_file(... |
# Python > Sets > The Captain's Room
# Out of a list of room numbers, determine the number of the captain's room.
#
# https://www.hackerrank.com/challenges/py-the-captains-room/problem
#
k = int(input())
rooms = list(map(int, input().split()))
a = set()
room_group = set()
for room in rooms:
if room in a:
... |
class Config:
device = 'cpu'
RBF_url = "https://github.com/Practical-AI/deep_utils/releases/download/0.2.0/version-RFB-320.pth"
RBF_cache = 'weights/vision/face_detection/ultra-light/torch/RBF/version-RFB-320.pth'
RBF = None
slim_url = "https://github.com/Practical-AI/deep_utils/releases/download/0.... |
alphabet = """1
2
3
4
5
6
7
8
9
10
11
12
"""
|
'''https://leetcode.com/problems/unique-paths/'''
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [1 for i in range(m)]
for i in range(1,n):
for j in range(1,m):
dp[j] += dp[j-1]
return dp[-1]
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def optimalDivision(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
if len(nums) == 1:
return str(nums[0])
if len(nums) == 2:
return str(nums[0]) + "/" + str(nums[1])
result = ... |
# ANALISADOR DE EXPRESSÕES NUMÉRICAS
"""Verifica se o número de parênteses abertos corresponde ao número de parênteses fechados."""
exp = '((a+(b/c)) * ( f - (c-d + e) ) ^3 + )4)'
#exp = str(input('Digite uma expressão: _ ')).strip()
print(f'Você digitou a expressão: \033[1;30;45m {exp} \033[m.')
# fatiando a string ... |
experiments_20 = {
'data':
{'n_experiments': 20,
'max_set_size': 500,
'network_filename': 'H_sapiens.net', #'S_cerevisiae.net'
'directed_interactions_filename': 'KPI_dataset',
'sources_filename': 'drug_targets.txt',
'terminals_filename': 'drug_expressions.txt',
... |
def notas(*n, sit=False):
"""
Analisa as notas e situação de vários alunos.
:param n: uma ou mais notas dos alunos.
:param sit: Opcional. Apresenta a situação.
:return: dicionário com várias informações da turma.
"""
dic={}
dic['total'] = len(n)
dic['maior'] = max(n)
dic['menor']... |
# 网络带宽计算
# print(100 / 8)
bandwidth = 100
ratio = 8
print(bandwidth / ratio)
|
"""
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3,
the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can,
there are at least 3 different ways to solve this problem.
"""
org = [1,2,3,4,5,6,7]
steps = 3
lis1 = org[steps+1:]
l... |
#Esercizio: Scrivere un programma in Python che calcola il triangolo di tartaglia
#def tartaglia(stop):
# if(stop < 0):
# return 1
# return tartaglia(stop-1)+stop
#print(tartaglia(5))
#Per trovare i numeri di fibonacci bisogna sommare i numeri del triangolo di tartaglia in diagonale, il primo è 1 il ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
student_list_file = "alunos.txt"
shelf_file = "shelf.shelf"
included_files_location = u"/home/bjorn/Dropbox/python_packages/bio_info_questions/bio_info_questions/files_to_be_included"
password_to_open_exam = u"zyxpep93"
... |
# pylint: disable=missing-docstring
TEST = map(str, (1, 2, 3)) # [bad-builtin]
TEST1 = filter(str, (1, 2, 3)) # [bad-builtin]
|
expected = [
{
"xlink_href": "elife00013inf001",
"type": "inline-graphic",
"position": 1,
"ordinal": 1,
}
]
|
APIYNFLAG_YES = "Y"
APIYNFLAG_NO = "N"
APILOGLEVEL_NONE = "N"
APILOGLEVEL_ERROR = "E"
APILOGLEVEL_WARNING = "W"
APILOGLEVEL_DEBUG = "D"
TAPI_COMMODITY_TYPE_NONE = "N"
TAPI_COMMODITY_TYPE_SPOT = "P"
TAPI_COMMODITY_TYPE_FUTURES = "F"
TAPI_COMMODITY_TYPE_OPTION = "O"
TAPI_COMMODITY_TYPE_SPREAD_MONTH = "S"
TAPI_COMMODITY_T... |
#
# PySNMP MIB module ASCEND-MIBSCRTY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBSCRTY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:28:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
while True:
s = input("Ukucaj nesto: ")
if s == "izlaz":
break
if len(s) < 3:
print("Previse je kratko.")
continue
print("Input je zadovoljavajuce duzine.")
#mozete zadavati druge komande za neki rad ovdej
|
pancakes = int(input())
if pancakes > 3:
print("Yum!")
else: #if pancakes < 3:
print("Still hungry!")
|
users_calculation = {}
def request_addition(user, num1, num2):
users_calcs = users_calculation.get(user)
if (users_calcs is None):
users_calcs = list()
users_calcs.append(num1+num2)
users_calculation[user] = users_calcs
def get_last_calculation(user):
users_calcs = users_calculation.ge... |
def x(a, b, c):
p = 5
b = int(x)
print(b) |
def teste(v, i):
valor = v
incremento = i
resultado = valor + incremento
return resultado
""" imprimindo 'a' passando os atributos '(10, 1)' """
a = teste(10, 1)
print("\n")
print(a)
"""
.............CLASSES E METODOS.............
Como se escrreve:
'def didatica_tech' # letras minusculas e underline se nec... |
print('*'*5, 'CONVERSOR DE TEMPERATURA', '*'*5)
temp = float(input('Informe a temperatura em °C: '))
f = temp*1.800 + 32
print(f'A temperatura de {temp:.1f}°C é equivalente a {f:.1f}°F.')
print('*'*10, '+++++', '*'*10)
|
# from https://en.wikipedia.org/wiki/Test_functions_for_optimization
#
# takes input parameters x,y
# returns value in "ans"
# optimal minimum at f(3,0.5) = 0
# parameter range is -4.5 <= x,y <= 4.5
def evaluate(x,y):
return (1.5 - x + x*y)**2 + (2.25 - x + x*y*y)**2 + (2.625 - x + x*y*y*y)**2
def run(self,Inputs):... |
# -*- coding: utf-8 -*-
def create():
resourceDict = dict()
return resourceDict
def addOne(resourceDict, key, value):
if (len(key)<=2):
return 'err'
if (key[0:2]!="##"):
print("key must be like '##xx' : %s " % key)
return 'err'
resourceDict[key] = value
return 'ok'
|
class DuplicateTagsWarning(UserWarning):
def get_warning_message(self, duplicate_tags, name):
return f"Semantic tag(s) '{', '.join(duplicate_tags)}' already present on column '{name}'"
class StandardTagsChangedWarning(UserWarning):
def get_warning_message(self, use_standard_tags, col_name=None):
... |
"""
write your first program in python
"""
print("helloworld in python !!")
|
a = float(input("1.Sayı:"))
b = float(input("2.Sayı:"))
c = str(input("Hangi işlemi yapmak istiyorsunuz (bolme,carpma,cikarma,toplama):"))
if c == "bolme"or c == "carpma"or c == "cikarma"or c == "toplama":
print(c,"işleminiz gerçekleştiriliyor...")
else:
print("İşleminiz gerçekleştirilemiyor.")
if c == "bolme"... |
def soma(n1,n2):
r = n1+n2
return r
def sub(n1,n2):
r = n1-n2
return r
def mult(n1,n2):
r = n1*n2
return r
def divfra(n1,n2):
r = n1/n2
return r
def divint(n1,n2):
r = n1//n2
return r
def restodiv(n1,n2):
r = n1%n2
return r
def raiz1(n1,n2):
r = n1**(0.5)
re... |
# Edit and set server name and version
test_server_name = '<put server name here>'
test_server_version = '201X'
# Edit and direct to your test folders on your server
test_folder = r'\Tests'
test_mkfolder = r'\Tests\New Folder'
test_newfoldername = 'Renamed folder'
test_renamedfolder = r'\Tests\Renamed folder'
... |
'''
Created on Aug 8, 2017
Check permutation: Given two strings, write a method to decide if one is a permutation of the other
Things to learn:
- a python set orders set content
- in a set, one uses == to compare same content
@author: igoroya
'''
def check_string_permuntation(str1, str2):
if len(str1) is not le... |
#
# PySNMP MIB module IEEE8021-MIRP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IEEE8021-MIRP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:52:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2021 all rights reserved
#
"""
A comprehensive test of arithmetic operator overloading
"""
class Node:
"""A sample object that supports algebraic expressions among its instances and floats"""
# public data
va... |
def comparison(start,end, path_to_file):
file = open(path_to_file)
for res in file:
pred_start = int(res.split(" ")[1])
pred_end = int(res.split(" ")[2].split("\t")[0])
if not (pred_end < int(start) or pred_start > int(end)):
return res.split("\t")[-1]
return ''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.