content stringlengths 7 1.05M |
|---|
n=int(input())
arr = []
for i in range(n):
arr.append(int(input()))
k=None
c=0
temp=[]
for i in range(n):
temp.append(abs(arr[0]-arr[i]))
k=max(temp)
if k<2:
k=2
for i in range(n):
c+=abs(k-arr[i])
k+=1
print(c)
|
class ActException(Exception):
def __init__(self, message):
super(ActException, self).__init__(message)
self.message = message
class ActLoginError(ActException):
def __init__(self, msg):
super(ActLoginError, self).__init__('Actifio Login Exception: %s' % msg)
self.msg = msg
class ActConnectError(... |
#Fibonacci Series :
def fib(n):
N = input("Enter no. : ") #User Input
try:
n = int(N) #Converting stirng value into integer
a = 0 #'a' & 'b' values are fixed for Fibonacci series
b = 1
if n == 1:
print(a) ... |
#a
"""
for each pair of items in the usorted list:
if the pair is out of order :
swap them
"""
#b
#The end of the unsorted list
"""end = len(lst) - 1
#Keep going until the last item of the list is reached
while end != 0 :
for each pair of items in the usorted list:
if the pair is out of order :
... |
a = "WWW"
b = 'WWW'
lrc = "I've let you down"
# lrc2 = 'I've let you down'
print(lrc);
# \t
# \n
sen = "Jack: \"You jump I jump\""
sen2 = 'Jack: "You jump I jump"'
print(sen);
print(sen2);
|
print('=====Desafio 053=====')
frase = str(input('Digite uma frase: ')).strip().upper()
palavras = frase.split()
junto = ''.join(palavras)
inverso = ''
for letra in range (len(junto)-1, -1, -1):
inverso += junto[letra]
print(junto, inverso)
if inverso == junto:
print('A frase digitada é um palíndromo')
else:
... |
class NotDefined:
pass
def has_descent_attrs(obj, *args):
i = obj
for attr_name in args:
if not hasattr(i, attr_name):
return False
i = getattr(i, attr_name)
return True
def get_descent_attrs(obj, *args, **kwargs):
default = kwargs.pop('default', NotDefined)
i = o... |
#%%
"""
- Flip Equivalent Binary Trees
- https://leetcode.com/problems/flip-equivalent-binary-trees/
- Medium
For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.
A binary tree X is flip equivalent to a binary tree Y if and only if we can make X ... |
"""
Meta-information about pe.
"""
__version__ = '0.3.2'
# Note: most of this file's contents has moved to setup.cfg
|
# Here go your api methods.
def get_products():
if request.vars['query'] is None:
product_list = db().select(db.r_products.ALL)
return response.json(dict(product_list=product_list))
else:
product_list = db(db.r_products.f_name.like(request.vars['query'] + '%') ).select()
return response.json(dict(product... |
class Emp:
def __init__(self, emp_id=0, name="", age=0, gender="", place="", salary=0, previous_company="", joining_date=""):
self._emp_id = emp_id
self._name = name
self._age = age
self._gender = gender
self._place = place
self._salary = salary
self._previo... |
def test_foo():
assert False
def test_bar():
assert False
|
with open("input", "r") as f:
count = 0
for line in f:
string = line.split(': ')[1]
fst = line.split(': ')[0]
letter = fst[-1]
fst = fst[:-1]
a = int(fst.split('-')[0])
a -= 1
b = int(fst.split('-')[1])
b -= 1
count += bool(string[a] == letter) != bool(string[b] == letter)
pri... |
sol = ""
for i in range (1,1000000):
sol = sol+str(i)
if len(sol) > 1000000:
break
ans = 1
for i in range(6):
ans = ans*int(sol[10**i-1])
print(ans) |
side = 1080
frames = 120
speed = 4000
def lsPts(inc):
steps = 1 + inc
size = 2
tr = 106.5
points = []
for i in range(steps):
t = i / 21 * pi
x = (size * t) * cos(t)
y = (size * t) * sin(t) - (tr/2)
points.append((x, y))
for i in range(-steps, 0):
t = i / ... |
def do_stuff():
print('stuff')
def do_other_stuff():
print('other stuff')
def branching(some_condition):
if some_condition is True:
do_stuff()
do_other_stuff()
|
def react(text):
stack = []
for letter in text:
if not stack:
stack.append(letter)
else:
l = stack[-1]
if letter != l and l.lower() == letter.lower():
stack.pop()
else:
stack.append(letter)
return len(stack)
d... |
class Node:
def __init__(self, data=None):
self.val = data
self.right = None
self.left = None
class BST:
def __init__(self, data=None):
self.tree = None if data is None else Node(data)
def isEmpty(self):
if self.tree == None:
return True
else:
... |
# Define a function searching for the longest word
def get_longest_word(words):
longest_word = ''
for word in words:
if len(word) > len(longest_word):
longest_word = word
return longest_word
wlist = [
['Python', 'creativity', 'universe'],
['interview', 'study', 'job', 'univers... |
class Loop(object):
"""
Repeatedly run and reschedule an action.
"""
def __init__(self, clock, action):
"""
Args:
clock: a clock function that returns a non-decreasing time.
action: the action to run.
reschedule: a function that reschedules this action. It m... |
# 布林值
boolean1 = True
boolean2 = False
# 要記得,python是開頭大寫,而且只有這種寫法正確
type(boolean1)
type(boolean2)
# ans: class bool
1 > 2
# ans: False
2 == 2
# ans: True
3 < 2
# ans: False
2 != 3
# ans: True
5 >= 3
# ans: True
3 <= 5
# ans: True
"real" == "read"
# ans: False
"Bye" == "bye"
# a... |
def create_tags_list(*tags):
tags_list = list(set(tags))
tags_list.sort()
return tags_list
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
# Quick return
if not head or... |
# cc71 meanMedianMode https://repl.it/student/submissions/1871422
'''
Write a function that, given a list of numbers, calculates the
mean, median, and mode of those numbers. Return a dictionary with
properties for the mean, median and mode.
For example:
mmm_dict = meanMedianMode([1,2,3,4,5,6,7,8,9,10,10])
print(mmm_di... |
"""translation tables are useful for mapping character changes (translations)"""
trans_table1 = "A Tesx Sxring".maketrans({"x": "t"})
trans_table2 = "A Tesx Sxring".maketrans("x", "t")
print(trans_table1)
print(trans_table2)
trans1 = "A Tesx Sxring".translate(trans_table1)
trans2 = "A Tesx Sxring".translate(trans_ta... |
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, other):
return Vector(self.x + other.x , self.y + other.y)
def sub(self, other):
return Vector(self.x - other.x, self.y - other.y)
def mag2(self):
return self.x ** 2 + self.y ** 2
... |
# Copyright 2016 F5 Networks 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-2.0
#
# Unless required by applicable law or agreed to in writi... |
#3
for row in range(8):
for col in range(6):
if (row==0) or (row==1 and col==4) or (row==2 and col==3)or (row==3 and col==2)or (row==4 and col==3)or (row==5 and col==4) or row==6:
print("*",end=" ")
else:
print(" ",end=" ")
print()
|
def main():
info('Waiting for minibone access')
wait('JanMiniboneFlag', 0)
info('Minibone released')
wait('MinibonePumpTimeFlag', 0)
acquire('FelixMiniboneFlag', clear=True)
info('minibone acquired')
|
def findFirstAndLast(arr, n, x) :
first = -1
last = -1
for i in range(0, n) :
if (x != arr[i]) :
continue
if (first == -1) :
first = i
last = i
if (first != -1) :
print( "First Occurrence = ", first,
" \nLast Occurrence = ", last)
else :
print("Not Found")
arr = [1, 2, 2, 2, 2, 3, 4, 7, ... |
#Config File for declaring and initializing global variables
data_glance_exit_flag = False
current_temp = 0
current_humidity = 0
current_soil = 0
current_float = 0
current_fan = 0
pumped = False
currently_lighting = False
|
arr = [1, 3, 5, 3, 1, 6, 3, 2]
print(arr)
s = set(arr)
# `{}`로 감싸진 건 해시맵 / 해시셋
print(s)
# `[]`로 감싸진 건 배열
print(list(s))
|
team_names = ['Pittsburgh Steelers', 'Baltimore Ravens', 'NE Patriots', 'Miami Dolphins',
'Indianapolis Colts', 'Jacksonville Jaguars', 'Denver Broncos', 'KC Chiefs',
'Green Bay Packers', 'Chicago Bears', 'Dallas Cowboys', 'Philadelphia Eagles',
'New Orleans Saints', 'Atlanta... |
# Time: O(31)
# Space: O(1)
# 1318 weekly contest 171 1/11/2020
# Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make a OR b == c. (bitwise OR operation).
# Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representa... |
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
table = {}
table[1] = 1
table[2] = 2
for i in range(1, n+1):
if i not in table:
table[i] = table[i-1] + table[i-2]
return table[n]
s = 3
solution = Solu... |
#!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'kǒngzuì'
CN=u'孔最'
NAME=u'kongzui34'
CHANNEL='lung'
CHANNEL_FULLNAME='LungChannelofHand-Taiyin'
SEQ='LU6'
if __name__ == '__main__':
pass
|
#!/usr/bin/env python
"""
_FwkJobReport_
FwkJobReport unit test
"""
__all__ = []
|
##f = []
##
##def factorial(n):
## result = n
## for i in range(1, n):
## if(i in f):
## result = i * f[f.index(i)]
## else:
## result = i * result
## f.append(result)
## print(result)
##
##factorial(3)
##factorial(4)
##n = int(input())
##arr = [1] * (n + 1)
##f... |
primeira_nota = float(input("Diga sua primeira nota: ").strip())
segunda_nota = float(input("Diga sua segunda nota: ").strip())
media = (primeira_nota + segunda_nota) / 2
if media < 5.0:
print(f"A sua média é igual a {media:.2f}. Você foi REPROVADO.")
elif media < 6.9:
print(f"A sua média é igual a {media:.2f... |
class Solution:
def __init__(self):
self.RED = 0
self.BLUE = 1
self.GREEN = 2
def minCost(self, costs: List[List[int]]) -> int:
if len(costs) == 0:
return 0
for idx in range(1, len(costs)):
prev_min_costs = costs[idx - 1]
... |
class Node:
def __init__(self, data=None, prev=None, next=None):
self.data = data
self.prev = prev
self.next = next
class DoublyLinkedList:
def __init__(self):
self.head = None
def insert_at_begining(self, data):
node = Node(data=data)
if self.head is None:... |
with open("top10000words.txt", 'r') as f:
allwords = f.readlines()
fiveletterwords = []
for word in allwords:
if len(list(word)) == 6:
fiveletterwords.append(word.lower())
with open('5lettertop10k.txt', 'w') as g:
g.writelines(fiveletterwords) |
#
# @lc app=leetcode.cn id=151 lang=python3
#
# [151] reverse-words-in-a-string
#
None
# @lc code=end |
# ------------------------------
# 277. Find the Celebrity
#
# Description:
# Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there
# may exist one celebrity. The definition of a celebrity is that all the other n - 1 people
# know him/her but he/she does not know any of them.
#
# ... |
f = open("example_22.txt", encoding="utf-8")
print(f.read())
"строка 1\nстрока 2\nстрока 3"
|
# calc the spawn in a factorial way would be nice in erlang or elixir...
def count_fishes(input, days):
vals = list(map(int, input.split(',')))
# Only need to calc for each unique
unique_ages = list(set(vals))
result = 0
for unique_age in unique_ages:
spawn = _calc_spawn([unique_age], d... |
"""
Ahora, te motivamos a escribir un programa en Python que solicite
el ingreso de tres criptomonedas, las cantidades y cotizaciones en Dólares
Americanos (USD) de cada una de éstas; además, debes validar que las tres criptomonedas
pertenezcan a las siguientes (BTC, BCC, LTC, ETH, ETC y XRP), y que las cantidades
y ... |
def format(discrepancies, margins = None):
if discrepancies == {}:
return "No Discrepancies Found"
inequal_messages = ""
missing_physical_message = ""
missing_digital_message = ""
valid_discrepancies = 0
for item, entry in discrepancies.items():
valid_discrepancies += 1
if entry["digital"] == None:
if en... |
'''
Simple hello world python modules.
'''
__name__ = "greetworld"
__version__ = 0.4
__author__ = 'Rajendra Kumar R Yadav'
__doc__ = '''
A simple Greet World module in Python
'''
|
class LRUCache(object):
def __init__(self, size):
self.size = size
self.cache = {}
self.priorities = []
def adjust(self, key):
item_index = self.priorities.index(key)
self.priorities[:] = self.priorities[:item_index] + self.priorities[item_index+1:]
self.priorit... |
def rounded_box_fn_icon(node):
return {
"shape": "box",
"style": "rounded",
}
def rounded_box_metric_icon(node):
return {
"shape": "box",
"style": "rounded",
}
def square_box_database_icon(node):
return {
"shape": "box",
}
def square_box_json_icon(no... |
#
# Simple Hello World Program
#
print("Hello Python")
print('Hello World') |
qtd = int(input()) # Quantidade de números
numeros = []
for i in range(0, qtd):
num = int(input())
if num != 0:
numeros.append(num)
else:
numeros.pop() # Se o número for 0, remove o último número adicionado
print(sum(numeros)) # Soma todos os números |
#085: Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente.
valor = list()
par = list()
impar = list()
print('=' * 50)
print(f'{"FILTRANDO NÚMEROS NA LISTA... |
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
max_cnt = 0
for num in set(nums):
cur_cnt = nums.count(num)
if cur_cnt > max_cnt:
max_cnt=cur_cnt
max_num = [num]
elif cur_cnt == max_cnt:
max_n... |
expected_output = {
"primary_load_time_percent":0,
"secondary_load_time_percent":0,
"one_minute_load_percent":1,
"five_minute_load_percent":1,
"ntp_time":"14:48:32.688 UTC Tue Mar 22 2022",
"smart_licensing_status":{
"export_authorization_key":{
"features_authorized":... |
TENTATIVE = [
"Antifascistas de Gerona intentan enseñar democracia a hostias a los 'fachas' de VOX",
"Condenado un inmigrante rumano por violar y dejar embarazadas a sus dos hijas",
"Detenido un marroquí por sacar el pene y restregárselo a una clienta en la cola de Decathlon",
"Vecinos de Tenerife evit... |
# coding: utf-8
#
atx_agent_version = "" # set from command line
|
#!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@contact: sinotradition@gmail.com
@copyright: License according to the project license.
'''
__all__ = ['wu3', 'wei4', 'yin2', 'shen1', 'hai4', 'you3', 'xu1', 'mao3', 'chen2', 'zi3', 'si4', 'chou3'] |
def CheckPossibility(num):
digits = [int(d) for d in str(num)]
lastDigit = 0
hasConsecutive = False
for i in digits:
if(lastDigit > i):
return False
if(lastDigit == i):
hasConsecutive = True
lastDigit = i
else:
if(hasConsecutive == F... |
'''
Faça um Programa que leia 4 notas, mostre as notas e a média na tela.
'''
soma = 0
for i in range(0,4,1):
num = float(input('Digite uma nota: '))
soma += num
i+=1
print('Media: '+soma/i) |
def spotRsiExceed(current_rsi):
if current_rsi > 70:
# The market may be overbought, it may become bearish
return -1
elif current_rsi < 30:
# the market may be ouversold, it may become bullish
return 1
return 0
|
class InsertError(RuntimeError):
def __init__(self, operation, cause):
self.operation = operation
self.cause = cause
|
with open('input.txt', 'r') as f:
s = f.readline()
n,m = [int(x) for x in s.split()]
out = []
if n > m:
while n + m:
if n:
out.append("B")
n -= 1
if m:
out.append("G")
m -= 1
else:
while n + m:
... |
class Constants:
LOGGER_NAME = "log4sdc-common"
LOGGER_LOG_LEVEL_ENV_VAR = "LOG_LEVEL"
LOGGER_DEFAULT_LOG_LEVEL = "WARN"
def __setattr__(self, attr, value):
if hasattr(self, attr):
raise Exception("Attempting to alter read-only value")
self.__dict__[attr] = value
|
class Solution:
def leap_year(self, year):
return ((year % 400 == 0) or (year % 100 != 0 and year % 4 == 0))
def date_to_int(self, year, month, day):
month_length = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
ans = day - 1
while month != 0:
month -= ... |
# 1018 - Cédulas
# https://www.urionlinejudge.com.br/judge/pt/problems/view/1018
# count_banknotes(Tuple[int, ...], int) -> Iterator[Tuple(int, int)]
def count_banknotes(banknotes, value):
counter = {}
for bkn in banknotes:
counter[bkn] = value // bkn
value %= bkn
return sorted(counter.ite... |
# 등차수열의 개수
n = int(input())
num_list = list(map(int, input().split(" ")))
count = 0
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if num_list[j] - num_list[i] == num_list[k] - num_list[j]:
count += 1
print(count) |
N,B,H,W =map(int,input().split())
ans = 9876543210
for i in range(H):
p = int(input())
L = list(map(int,input().split()))
for i in L:
if i >=N:
if p*N <= B and p*N < ans:
ans = p*N
if ans == 9876543210:
print("stay home")
else:
print(ans) |
# decorator function
def mymypy(types):
def wrap(func):
def inner(*args):
for t, a in zip(types, args):
if not isinstance(a, t):
raise TypeError(f'Argument: {a} is not type {t}')
return func(*args)
return inner
return wrap
# --- testi... |
# Data directories
train_data_path = "./finished_files/chunked/train_*.json"
eval_data_path = "./finished_files/val.json"
decode_data_path = "./finished_files/test.json"
vocab_path = "./finished_files/vocab"
log_root = "./log"
# Hyperparameters
hidden_dim = 256
emb_dim = 128
batch_size = 8
max_enc_steps = 400
max_dec_... |
class BaseProfileVisualizer:
def __init__(self, framework=None, visualizer=None):
self.framework = framework
self.visualizer = visualizer
self.profiles = []
def set_profiles(self, profiles):
""""""
if len(profiles) <= 1:
self.profiles = [profiles]
els... |
# Give yourself a nice cheer -
# print out Go Whateveryournameis!
print( )
# Did you get an error?
# Remember that you need to wrap something around text...
|
def select_tower(tower_selected, tower):
if tower_selected:
move_disk(tower_selected, tower)
return None
else:
return tower
def move_disk(from_tower, to_tower):
disk = from_tower.pop()
if not disk:
return False
if can_move(disk, to_tower):
to_tower.append(d... |
def dedupe_and_sort(sequence, first=None, last=None):
"""
De-dupe and partially sort a sequence.
The `first` argument should contain all the items that might appear in
`sequence` and for which the order (relative to each other) is important.
The `last` argument is the same, but matching items will... |
nums = (int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite o último número: ')))
print(f'Você digitou os números: {nums}')
if nums.count(9) != 0:
print(f'o número 9 apareceu {nums.count(9)} vezes')
if nums.count(3) ... |
class OTRSException(Exception):
pass
class HTTPMethodNotSupportedError(OTRSException):
pass
class OTRSBadResponse(OTRSException):
pass
class AuthError(OTRSException):
pass
class AccessDeniedError(OTRSException):
pass
class InvalidParameterError(OTRSException):
pass
class ArgumentMiss... |
# cmdline: -O
# test optimisation output
print(__debug__)
assert 0
|
HOST = 'nhc2.local'
USER = 'username'
PASS = 'password'
# For hobby API 8884
PORT = 8883 |
"""Bind all submodules needed for eventuals."""
load("@com_github_3rdparty_eventuals//bazel:submodule_repository.bzl", "submodule_repository")
def submodules(external):
"""Creates repositories for each submodule.
Args:
external: whether or not we're invoking this function as though
thou... |
# Copyright 2021 Sony Corporation.
#
# 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 wri... |
api_key = ''
api_secret = ''
# number of seconds before bittrex request timesout
timeout = 5 |
expected_output = {
'vrf':
{'default':
{'address_family':
{'ipv4':
{'instance':
{'1':
{'areas':
{'0.0.0.0':
{'database':
... |
# Right justify a string to column 70 of the screen
def rightjustify(sig):
full_line = ""
num_chars = len(sig)
blank = 70 - num_chars
full_line += " "*blank + sig
pass
print(full_line)
rightjustify("monty")
|
def decimal_to_binary(n):
if n > 1: decimal_to_binary(n//2)
print(n % 2, end = '')
try: decimal_to_binary(int(input("Enter an Integer to Covert into Binary: ")))
except ValueError: print("Input is not an integer.")
print()
|
'''
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.
Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number ... |
#programa que recebe uma lista até o usuario decidir parar, e retorna a quantidade de valores na lista, a ordem decresente, e se a lista possui o numero 5;
lista = []
while True:
lista.append(int(input('Digite um valor: ')))
continuar =' '
while continuar not in 'SN':
continuar = input('D... |
#!/usr/bin/env python3
"""This file contains the health check functions used on a service bundle.
"""
|
n = input()
my_set = set()
for item in input().split():
my_set.add(item)
m = input()
for item in input().split():
if item in my_set:
print(1)
else:
print(0) |
class Observable:
def __init__(self):
self._observers = []
def register(self, observer):
if observer not in self._observers:
self._observers.append(observer)
def unregister(self, observer):
if observer in self._observers:
self._observers.remove(observer)
... |
class Script(object):
START_MSG = """<b>🙋♂️Hy {},</b>
<b>ഞാൻ ഒരു ഗ്രൂപ്പ് മാനേജർ ബോട്ട് ആണ്, എന്നെ കെഎൽ റോക്കേഴ്സ് ഗ്രൂപ്പിന് വേണ്ടി മാത്രമാണ് എന്നെ നിർമിച്ചിരിക്കുന്നത</b>
"""
HELP_MSG = """
<b>നീ ഏതാ..... ഒന്ന് പോടെയ് അവൻ help ചോയ്ച്ച് വന്നിരിക്കുന്നു😤...I'm Different Bot U Know</b>
"""
ABOUT_M... |
def menu():
print("Selecione a operação desejada:\n")
print("1. (COMPILE) Compilar um programa Assembly em hex")
print("2. (LOAD) Carregar um programa hex na memória")
print("3. (MEM) Olhar estado atual da memória")
print("4. (RUN) Rodar programa na memória")
print("x. (EXIT) Sair"... |
class Solution:
def lengthOfLongestSubstring(self, s):
dicts = {}
maxlength = start = 0
for i,value in enumerate(s):
if value in dicts:
sums = dicts[value] + 1
if sums > start:
start = sums
num = i - start + 1
... |
# -*- coding: utf-8
# http://stackoverflow.com/questions/2082152/case-insensitive-dictionary
class CaseInsensitiveDict(dict):
def __setitem__(self, key, value):
super(Caseinsensitivedict, self).__setitem__(key.lower(), value)
def __getitem__(self, key):
return super(Caseinsensitivedict, self)... |
def twoSum(nums: list, target: int) -> list:
"""
כתבו את תוכן הפונקציה - כך שהיא תחזיר רשימה של שני אינדקסים,
כך שסכום המספרים הנמצאים באינדקסים האלה שווה למספר המטרה:
nums = [1, 2, 3, 4],
target = 6
output: [1, 3] --> nums[1] + nums[3] = 2 + 4 = 6
"""
for i in range(len(nums)):
... |
student_name = input()
count = 0
count_fail = 0
grades = []
grade = float(input())
while count < 12:
if grade < 4:
count_fail += 1
if count_fail > 1:
print(f"{student_name} has been excluded at {count} grade")
exit()
grades.append(grade)
else:
grades.appe... |
#
# PySNMP MIB module PDN-MPE-HEALTH-AND-STATUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-MPE-HEALTH-AND-STATUS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:39:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... |
class Eval(object):
def __init__(self, param):
self.__str = param.get('value')
self.__length = param.get('length',100000)
self.__counter = 0
def next(self):
self.__counter += 1
if self.__counter > self.__length:
raise StopIteration
value = self.__str
return {'value': value}
def length(self):
r... |
#!/usr/local/bin/python3
# Em caso de erros após o arquivo ter sido aberto há um risco do a
# rquivo permanecer aberto, neste caso usando try & finally mesmo
# que ocorra o erro o bloco de finally será executado
try:
arquivo = open('pessoas.csv')
for registro in arquivo:
print('Nome: {}, Idade: {}'.fo... |
n=int(input())
a=""
for i in range(1,n+1):
a+=str(i)
print(a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.