content stringlengths 7 1.05M |
|---|
def test_data(make_napari_viewer):
viewer = make_napari_viewer()
n = len(viewer.layers)
viewer.open_sample("napari-basicpy", "sample_data")
assert len(viewer.layers) == (n + 1)
# NOTE
# assert viewer.layers[0].dtype == np.uint8
|
class BaseAPIException(Exception):
status_code = 500
def __init__(self, code='api_error', msg='Unexpected error'):
super().__init__(msg)
self.code = code
self.msg = msg
def to_dict(self):
return {
'code': self.code,
'msg': self.msg
}
class ... |
print(list(range(5)))
print(list(range(5, 10)))
print(list(range(0, 10, 2)))
print(list(range(10, 0, -2)))
print(list(range(0, 10, -2)))
|
def event():
print('start yield')
one = yield 'get_one' # return next(task) and yield next(task.send('set_two'))
assert(one == 'set_two')
print(one)
yield 'get_two' # return next(task) and yield next(task.send('set_two'))
print('exit yield')
yield # yield next() to exit or raise StopIteration
task = event()
ru... |
class Solution:
def checkOnesSegment(self, s: str) -> bool:
s = list(s)
ind = s.index('1')
while ind<len(s) and s[ind] == '1':
s[ind] = '0'
ind += 1
if '1' in s:
return False
else:
return True |
# Solution to problem 4
# Rebecca Turley, 2019-03-21
# Collatz.py
# The programme invites the user to enter a number.
n = float (input ("Please enter a number "))
while n != 1 :
# The condition states that while n (the number entered in the previous step by the user) is not equal to 1 so the steps will be run unt... |
mochila = ['machado', 'camisa', 'comida', 'agua']
print(mochila)
#alterar lista
mochila[2] = 'laranja'
print(mochila)
# manipular lista
print('---------- manipular listas')
mochila.append('bota') #adicionando
print(mochila)
mochila.insert(1,'meia') #adicionar em posição especifica
print(mochila)
del mochila[2] #delet... |
question_data = [
{"text": "A slug's blood is green.", "answer": "True"},
{"text": "The loudest animal is the African Elephant.", "answer": "False"},
{"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"},
{"text": "The total surface area of a human lungs is the size of ... |
class AbsValidator:
"""The parent class for all validators.
It defines the functions that all validator plugins have to implement and overwrite.
"""
def validate_file(self, file_path):
""" The function validate_file is the main workhorse and connection to the rest of the project.
... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def serialize(root):
def build_string(node):
if node:
vals.append(str(node.val))
build_string(node.left)
build_string(node.right)
else:
... |
expected_output = {
'lisp_id': {
0: {
'site_name': {
'Shire': {
'instance_id': {
4100: {
'eid_prefix': {
'192.168.1.0/24': {
'last_registere... |
#%% Tables creation
session_table_create = '''
CREATE TABLE IF NOT EXISTS session_library (
session_id bigint,
item_in_session int,
artist_name text,
song_title text,
song_length float,
PRIMARY KEY (session_id, item_in_session)
)
'''
user_table_create = '''... |
N = int(input())
A = input().split()
for i in range(N):
print(A[N-i-1] , end=" ")
|
a=2
b=7
c=a // b
print(c)
|
# question can be found on leetcode.com/generate-a-string-with-characters-that-have-odd-counts/
class Solution:
def generateTheString(self, n: int) -> str:
if n // 2 == 1:
return "a" * (n - 2) + "b" + "c"
else:
return "a" * (n - 2) + "b"
|
#! /usr/bin/env python
def say_name():
"""
Asks for name and print it
"""
name = input("Name: ")
print(name)
# say_name()
def add(num1=1, num2=2):
return num1 + num2
# sum = add()
# print("Sum is {0}".format(sum))
def madlibs(name, noun="sneakers", adjective="red"):
return "{0} has ... |
"""
this is a regional comment
"""
#print('hello world') # this is a line comment
#print( type(123) )
#print ( type (123.) )
#print( type('123') )
#print( "hello world" )
#print( 'hello world' )
#print ( "Tom's cat" )
#print(2.**3)
my_int = 123
print(my_int)
my_int = 321
print(my_int)
my_float = 123.
my_st... |
def f1(w):
def g1(x, y, z):
print(w, x, y, z)
return g1 # as in f1 it return g1 this is currying
my_f1 = f1(11)
my_f1(12, 13, 14)
|
# Authors: Kartik Ramasubramanian <r.kartik@berkeley.edu>
# License: BSD 3 clause
# functions shared across transformers
def _define_variables(variables):
# Check that variable names are passed in a list.
# Can take None as value
if not variables or isinstance(variables, list):
variables = variabl... |
numero=int(input("Dame un numero"))
suma=0
for i in range(0,numero+1):
for j in range(1,i+1):
suma=suma+j
print(suma) |
class Conf(object):
KEY = 'conf'
@staticmethod
def addParserItems(subparsers):
parser = subparsers.add_parser(Conf.KEY, help='Process a ConfLists.txt file to configure accel builds.')
parser.add_argument('dir', type=str, help='Location of the ConfLists.txt file.')
@staticmethod
def f... |
# -*- coding: utf-8
class ParseException(Exception):
"""
Thrown by Unke parser in case of syntax errors
"""
def __init__(self, message, line, col):
super(ParseException, self).__init__("{}, line {}:{}".format(message, line, col))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 19:28:11 2019
@author: nehap
"""
"""
Generate 1 to 10 tables
"""
if __name__=="__main__":
n=10
print("Output:")
for i in range(1,n+1):
for j in range(1,n+1):
print(i*j, end=" ")
print("\r") |
class SimplifyHelperMixin:
def max(self, *args, **kwargs):
self.simplify()
return super(SimplifyHelperMixin, self).max(*args, **kwargs)
def min(self, *args, **kwargs):
self.simplify()
return super(SimplifyHelperMixin, self).min(*args, **kwargs)
def eval(self, e, n, *args, *... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 13:28:57 2019
@author: mehrdad
"""
def convert_mode_to_tsmode(mode):
modemap = dict(train='RAIL', metro='SUBWAY')
if mode in modemap:
return modemap[mode]
else:
return str.upper(mode)
|
class Node:
def __init__(self,value):
self.value = value
self.next = None
head = Node("1st Node")
head.next = Node("2nd Node")
head.next.next = Node("3rd Node")
def iter_linked_list(node):
while node is not None:
print(node.value)
node = node.next
head.next.next.next = Node("4... |
"""
EEWMap - Tests
Unittest - Used to test modules and utilities.
"""
|
SOCKET_SLEEP = 2
MAX_RETRIES = 7
RESOURCES_CHECK = 7
CHECK_DELAY = 5
|
# Author: OMKAR PATHAK
# Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of
# its proper positive divisors, that is, the sum of its positive divisors excluding the number itself
# (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the ... |
#================================================================
#
# File name : configs.py
# Author : PyLessons
# Created date: 2020-08-18
# Website : https://pylessons.com/
# GitHub : https://github.com/pythonlessons/TensorFlow-2.x-YOLOv3
# Description : yolov3 configuration file
#
#=====... |
if l >=2:
user = sys.argv[1]
else:
user = input("Enter the username or ID (do not include the @ symbol): ")
try:
target = int(user)
except:
target = user
|
""" version
Note:
__version__:
indicates the version of the ansible_navigator applications
__version_collection_doc_cache__:
indicates the version of the schema of the collection doc cache
this is checked during initialization, if the version of the cache
differes from below, the cache will be rebuilt. This shoul... |
# Copyright 2014 Google Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
{
'variables': {
'shaka_code': 1,
},
'targets': [
{
'target_name': 'libpackager',
... |
class Solution:
def shortestPalindrome(self, s: str) -> str:
t = s[::-1]
for i in range(len(t)):
if s.startswith(t[i:]):
return t[:i] + s
return t + s
|
class Rectangle:
def __init__(self, offset, size, id):
self.offset = (int(offset[0]), int(offset[1]))
self.size = (int(size[0]), int(size[1]))
self.id = id
def fillRect(self, matrix):
for i in range(self.offset[0], self.offset[0] + self.size[0]):
for j in range(self.offset[1], self.offset[1] + self.size[1... |
#encoding=utf-8
class Tree_Node:
val = None
lChild = None
rChild = None
parent = None
height = None
def __init__(self, val):
self.val = val
self.lChild = None
self.rChild = None
self.parent = None
self.height = None
def output(self):
... |
# -*- coding: utf-8 -*-
'''
Contains exception classes used by vdirsyncer. Not all exceptions are here,
only the most commonly used ones.
'''
class Error(Exception):
'''Baseclass for all errors.'''
def __init__(self, *args, **kwargs):
for key, value in kwargs.items():
if getattr(self, key... |
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load("@language_support_ts_deps//eslint:index.bzl", _eslint_test = "eslint_test")
load("@os_info//:os_info.bzl", "is_windows")
def eslint_test(name, srcs, tsconfig = ":tsconfig.json"... |
"""
This module contains the result sentences and intents for the German version
of the Assistant information app.
"""
# Result sentences
RESULT_ASSISTANT_APPS = "Ich habe {} apps: {}."
RESULT_ASSISTANT_ID = "Meine ID ist {}."
RESULT_ASSISTANT_INTENTS = "Ich kenne {} Befehle."
RESULT_ASSISTANT_NAME = "Mein Name ist {}... |
def ting(*args):
for arg in args:
yield from funcOne(arg)
yield from funcTwo(arg)
def funcOne(arg):
for i in range(10):
yield "funcOne says: " + arg
def funcTwo(arg):
for i in range(10):
yield "funcTwo says: " + arg
def main():
for blink in ting("tong", "tim", "tin... |
#
# Licensed under the LICENSE.
# Copyright 2017, Sony Mobile Communications Inc.
#
'''
get_node_from_keydict
'''
def get_node_from_keydict(section, rack, tier, keydict_kc):
"""
get_node_from_keydict
:param section:
:param rack:
:param tier:
:param keydict_kc:
:return:
"""
key = s... |
"""
Built-in sum function be combined with Python’s
comprehension syntax to compute the sum of all numbers in an n×n data
set, represented as a list of lists.
"""
def sum_elements(data_set: list) -> float:
return sum(map(sum, data_set))
def sum_elements_comprehesion(data_ = list) -> float:
pass
... |
# Advent of Code day 22
# Solution part 1
p1 = [6, 25, 8, 24, 30, 46, 42, 32, 27, 48, 5, 2, 14, 28, 37, 17, 9, 22, 40, 33, 3, 50, 47, 19, 41]
p2 = [1, 18, 31, 39, 16, 10, 35, 29, 26, 44, 21, 7, 45, 4, 20, 38, 15, 11, 34, 36, 49, 13, 23, 43, 12]
emptytest = False
finaldeck = []
def round(p1, p2):
global emptytes... |
path_folder = '../data' #Path to where train and testing lists are located
class_mapping = '../action_classes.json'
saved_models_dir = 'saved_models/'
logs = 'logs/'
|
"""
Capstone Team Project. Sets the ROBOT NUMBER for YOUR team's robot.
Winter term, 2019-2020.
"""
def get_robot_number():
my_robot_number = None
return my_robot_number
# --------------------------------------------------------------------------
# TODO: 1. Set my_robot_number in the above to YOU... |
"""The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single q... |
valor1=int(input("Informe o primeiro valor\n"))
valor2=int(input("Informe outro qualquer valor\n"))
soma = valor1 + valor2
print(" a soma é :",soma) |
# Keeps asking for numbers until 0 is entered.
# Prints the average value.
count = 0
sum = 0.0
number = 1 # set to something that will not exit the while loop immediately.
print("Enter 0 to exit the loop.")
while number != 0:
number = float(input("Enter a number: "))
if number != 0:
count = count + 1... |
# Module used by stardoc to generate API documentation.
# Not meant for use by bazel-gazelle users.
"""
Extending Gazelle
=================
Gazelle started out as a build file generator for Go projects, but it can be
extended to support other languages and custom sets of rules.
To extend Gazelle, you must do three th... |
# Configuration file
token = 'put here your token'
# Bot owner's username
owner_username = 'alexander_baransky496'
|
##############################################################################
#copyright 2012,Hamid MEDJAHED (hmedjahed@prologue.fr) Prologue #
#Licensed under the Apache License, Version 2.0 (the "License"); #
#you may not use this file except in compliance with the License. #
#You... |
# -*- coding: utf-8 -*-
'''
:depends: kazoo
:configuration: See :py:mod:`salt.modules.zookeeper` for setup instructions.
ACLS
~~~~
For more information about acls, please checkout the kazoo documentation.
http://kazoo.readthedocs.io/en/latest/api/security.html#kazoo.security.make_digest_acl
The following options c... |
def harness(p):
if 'Hello world!' not in p.readline():
return False
return True
|
kelvin = float(input('Entre com a temperatura em Kelvin: '))
c = kelvin - 273.15
print(f'A temperatura em Kelvin convertida para Celsius é de: {c}')
|
x = int(input())
dict = {}
for i in range(0, x):
inputarray = input().split()
marks = list(map(float, inputarray[1:]))
dict[inputarray[0]] = sum(marks)/float(len(marks))
print("%.2f"% dict[input()]) |
print (True and True)
print (False and True)
print (1 == 1 and 2 == 20)
print ("test" == "test")
print (1 == 1 or 2 != 1)
print (True and 1 == 1)
print ( False and 0 != 0 )
print ( True or 1 == 1)
print ( "test" == "testing")
print ( 1 != 0 and 2 == 1)
print ( "test" != "testing")
print ( "test" == 1)
print ( not (True... |
TASK_STATE = {"NoPlan":1, "Planed":2, "MovingToSouce":3}
class Task:
def __init__(self, task_id:int) -> None:
self.States = {"NoPlan":1, "Planed":2, "MovingToSouce":3}
self.State = self.States["NoPlan"]
self.task_id = task_id
self.SourceStation_id = 0
self.TargetStation_id ... |
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
n = len(buildings)
if n == 0:
return []
if n == 1:
x_start, x_end, y = buildings[0]
return [[x_start, y], [x_end, 0]]
left_skyline = self.getSkyline(buildings[:n//... |
#!/usr/bin/env pypy
t, n = map(int, raw_input().split())
[raw_input() for i in xrange(n - 1)]
verdict = raw_input().strip()
if verdict == 'Random':
exit(-1)
|
def calculator(*args, **kwargs):
result = args[0]
if 'operation' in kwargs.keys():
for arg in args[1:]:
if kwargs['operation'] == '+':
result = result + arg
elif kwargs['operation'] == '-':
result = result - arg
elif kwargs['operation']... |
"""
Common global variables / functions.
"""
PKL_LST_EXT = '.pkl_lst'
PKL_DIC_EXT = '.pkl_dic'
LOG_EXT = '.log'
NATIVE_COUNTRIES = {'Australia', 'England', 'Ireland', 'Scotland', 'Wales', 'UK', 'New Zealand', 'US', 'Canada'}
# COUNTRIES_ORDER = ['UK', 'Scotland', 'England', 'Wales', 'Ireland',
# 'Ne... |
#!/usr/bin/env python
# coding: utf-8
# In[19]:
idade = input("Informe a sua idade: ")
print(idade, type(idade))
# In[24]:
idade = int(idade)
print(idade, type(idade))
# In[26]:
print(float('123.52'))
print(str(123.25))
print(bool(''))
print(bool('abc'))
print(bool(0))
print(bool(-2))
# In[32]:
salario =... |
"""
1. Clarification
2. Possible solutions
- Backtracking v1
- Backtracking v2
3. Coding
4. Tests
"""
# T=O(2^n), S=O(n)
class Solution:
def __init__(self):
self.valid_expressions = set()
self.min_removed = math.inf
def remaining(self, string, index, left_count, right_count, expr, rem... |
''' While Loops
Used to execute a set of statements(code) continuously as long as a condition is True.
The while loop needs
''' |
class ClientsManager:
SocketsList = {"Sockets": {}}
def AddSocket(PlayerID, Sockets):
ClientsManager.SocketsList["Sockets"][PlayerID] = Sockets
def RemoveSocket(PlayerID):
try:
ClientsManager.SocketsList["Sockets"].pop(PlayerID)
except KeyError:
print(f"Can... |
STOP_WORDS = set(
"""
a abo ale ani
dokelž
hdyž
jeli jelizo
kaž
pak potom
tež tohodla
zo zoby
""".split()
)
|
def heapify_node(arr, i, n):
l = 2*i + 1
r = 2*i + 2
smallest = i
if l < n and arr[l] < arr[smallest]:
smallest = l
if r < n and arr[r] < arr[smallest]:
smallest = r
if smallest != i:
arr[smallest], arr[i] = arr[i], arr[smallest]
arr = heapify_node(arr, small... |
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
# dimensions[0] = 100
# print(dimensions)
for dimension in dimensions:
print(dimension)
dimensions = [100, 300]
for dimension in dimensions:
print(dimension) |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
res = ListNode(0)
cur = res
while l1 and l2:
if l1.val > l2.val:
c = Lis... |
"Shows how to enable both worker mode and use_angular_plugin to make a drop-in replacement for ng_module"
load("@npm//@bazel/typescript:index.bzl", "ts_library")
def ng_ts_library(**kwargs):
angular_assets = kwargs.pop("assets", []) + kwargs.pop("angular_assets", [])
ts_library(
compiler = "//tools:ts... |
abc = sorted([chr(ord("A") + x) for x in range(26)])
steps, amount = dict((x, set()) for x in abc), dict((x, 0) for x in abc)
for line in open("inputs/day07.input"):
l = line.split()
before, after = l[1], l[7]
steps[after].add(before)
amount[after] += 1
done, order = set(), ""
while abc:
for idx, v... |
"""Provides methods for extending exceptions."""
class _Message(object):
"""
Class for storing custom error messages in exceptions.
"""
def __init__(self, str):
self._str = str
def __str__(self):
return self._str
def add_message(exception, message):
"""
Embeds an error m... |
n = input()
names = []
for i in range(n):
name = raw_input()
names.append(name)
if(all(names[i] <= names[i+1] for i in xrange(len(names)-1))):
print("INCREASING")
elif(all(names[i] >= names[i+1] for i in xrange(len(names)-1))):
print("DECREASING")
else:
print("NEITHER") |
"""This module maps SWC IDs to their registry equivalents."""
DEFAULT_FUNCTION_VISIBILITY = "100"
INTEGER_OVERFLOW_AND_UNDERFLOW = "101"
OUTDATED_COMPILER_VERSION = "102"
FLOATING_PRAGMA = "103"
UNCHECKED_RET_VAL = "104"
UNPROTECTED_ETHER_WITHDRAWAL = "105"
UNPROTECTED_SELFDESTRUCT = "106"
REENTRANCY = "107"
DEFAULT_S... |
def parameterized(names, params):
def decorator(func):
func.param_names = names
func.params = params
return func
return decorator
|
# factorial(n) = n * (n-1) * (n-2) * ... * 3 * 2 * 1
def factorial(n):
res = 0
for i in range(0, n):
res *= i
return res
# Add your tests here
def test_factiorial():
assert 1 == factorial(1)
assert 5 == factorial(120)
|
matriz = [ [0, 1, 2],
[3, 4, 5],
[6, 7, 8], ]
'''
0 | 1 2
---
3 4 5
---
6 7 | 8
Ir do 0 ao 8
sem bater nas paredes
'''
# Variável onde seu índice representa a posíção no labirinto
# E seu valor representa os possíveis lugares para se mover
nos = [
[3],#... |
class DB_Exceptions(Exception):
def __init__(self, name, value=None):
self.name = name
self.value = value
def __str__(self):
error_format = {"DB_CONNECT:":
f'''Currently only the following objects are supported
Oracle | mysql ->sq... |
__author__ = 'cjoakim'
class Constants(object):
@classmethod
def uom_miles(cls):
return 'm'
@classmethod
def uom_kilometers(cls):
return 'k'
@classmethod
def uom_yards(cls):
return 'y'
@classmethod
def units_of_measure(cls):
return ('m', 'k', 'y')
... |
# https://leetcode.com/problems/search-in-rotated-sorted-array/
class Solution:
def search(self, nums: List[int], target: int) -> int:
#if len(nums) == 1 and nums[0] == target:
# return 0
left, right = 0, len(nums) - 1
while left <= right:
... |
class Report:
def __init__(self, name="", data=""):
self.name=name
self.data=data
class LeaveRecord:
def __init__(self, gradeFrom, gradeTo, weeks, data=""):
self.gradeFrom=gradeFrom
self.gradeTo=gradeTo
self.weeks = weeks
self.data=data
class MainData:
def ... |
# establish arg function with "you" as default.
# return a customized string from func
def two_fer(name='you'):
# return string
return f'One for {name}, one for me.'
|
# Your car is old, it breaks easily. The shock absorbers are gone and you think it can handle about 15 more bumps before it
# dies totally. Unfortunately for you, your drive is very bumpy! Given a string showing either flat road ("_") or bumps ("n"),
# work out if you make it home safely. 15 bumps or under, return "Woo... |
RIGHT = 'RIGHT'
LEFT = 'LEFT'
STRAIGHT = 'STRAIGHT'
DIR_LINE = {'>': '-', 'v': '|', '<': '-', '^': '|'}
GLOB = {'last_id': -1}
CLEANED_ID = []
class Cart:
def __init__(self, i, j, direction):
GLOB['last_id'] += 1
self.id = GLOB['last_id']
self.i = i
self.j = j
self.dir = d... |
"""This module has a __version__ that requires runtime interpretation"""
__version__ = ".".join(["1", "2", "3"])
|
""" Rotating a matrix Anticlockwise by 90 degrees : """
"""Solution: """
def rotate_anti(arr):
n = len(arr)
for i in range(len(arr)):
for j in range(i+1, len(arr[i])):
arr[i][j], arr[j][i] = arr[j][i], arr[i][j]
for i in range(len(arr)//2):
for j in range(len(arr[i])):
... |
mst_conversation_encounter_dummy = 0
mst_conversation_encounter = 1
mst_castle_attack_walls_molda_ram = 2
mst_castle_attack_walls_molda_ladder_belfry = 3
mst_castle_attack_walls_molda_ladder_two = 4
mst_castle_attack_walls_molda_open_gate = 5
mst_castle_attack_walls_molda_infil_river = 6
mst_castle_attack_walls_molda_u... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class UserDeleteParameters(object):
"""Implementation of the 'UserDeleteParameters' model.
Specifies the users to delete on the Cohesity Cluster.
Attributes:
domain (string): Specifies the domain associated with the users to
del... |
def Over9000(params, alpha=0.5, k=6, *args, **kwargs):
ralamb = Ralamb(params, *args, **kwargs)
return Lookahead(ralamb, alpha, k)
RangerLars = Over9000 |
# -*- coding: utf-8 -*-
source1 = """
Тилигульский лиман
Одесский Клуб Рыболовов Здравствуйте, VinsT!
мирон 2 опубликовал комментарий в тему, Тилигульский лиман
мирон 2 опубликовал(а): 14 часа назад, Ігор сказал:
Можно связывать канатом использованые шины и притапливать в лимане. Их быстро освоят мидии и другие ... |
'''Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.'''
print('-' * 14)
print('NÚMEROS PRIMOS')
print('-' * 14)
n = int(input('Digite um número inteiro: '))
cont = 0
for c in range(1, n + 1):
if n % c == 0:
cont = cont + 1
if cont == 2:
print('O número é PRIMO')
e... |
"""
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
Suppose the following input is supplied to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '55', '33', '12', '98']
('34', '67', '55', '33', '12', '98... |
"""
Some of the functions have a bit cumbersome behavior when we deal with
positional and keyword arguments.
Write a function that accept any iterable of unique values and then
it behaves as range function:
import string
assert = custom_range(string.ascii_lowercase, 'g') == ['a', 'b', 'c', 'd', 'e', 'f']
assert = ... |
__version__ = "0.3.4"
# The USGS API endpoint
USGS_API_DEPRECATED = "https://earthexplorer.usgs.gov/inventory/json/v/1.4.0"
USGS_API = "https://m2m.cr.usgs.gov/api/api/json/stable"
#
# Two catalogs are available for querying
#
CATALOG_NODES = ["EE", "HDDS"]
# http://earthexplorer.usgs.gov/
EARTH_EXPLORER_CATALOG_N... |
# inFile = open('input.txt', 'r', encoding='utf8') # - для coursera с указанием юникода
inFile = open('input.txt', 'r')
outFile = open('output.txt', 'w', encoding='utf8')
l = [list(line.strip().split()) for line in inFile]
new_l = []
N = int(*l[0])
for line in l[1:]:
a = sorted(list(map(int, line[-1:-4:-1]))... |
def main(request, response):
headers = [("Content-Type", "text/javascript"), ("Cache-control", "public, max-age=100")]
body = "throw('fox');"
return 200, headers, body
|
n1 = float(input("Insira a nota da primeira prova: "))
n2 = float(input("Insira a nota da segunda prova: "))
n3 = float(input("Insira a nota da terceira prova: "))
n4 = float(input("Insira a nota da quarta prova: "))
media = (n1+n2+n3+n4)/4
print("A média desse estudante foi {.:2f}: ",format(media)) |
# Inspired by https://github.com/oceboy233/boost
def boost_library(
name,
srcs = None,
textual_hdrs = None,
defines = None,
linkopts = None,
deps = None,
sha256 = None):
return {
'name': name,
'version': 'boost-1.75.0',
'srcs': srcs,
'textual_hdrs': textu... |
"""
变量语法
"""
# 写法1:变量名 = 数据
name01 = "悟空"
# 写法2:变量名1, 变量名2 = 数据1, 数据2
name02, name03 = "猪八戒", "唐僧"
# 写法3:变量名1 = 变量名2 = 数据
name04 = name05 = "小白龙"
name06 = "孙悟空"
# 变量给变量赋值
name07 = name06
|
# -*- coding: utf-8 -*-
class Queue:
def __init__(self):
self.items = []
self._sizes = 0
def enqueue(self, item):
# None can be added to queue
self.items.insert(0, item)
self._sizes += 1
def dequeue(self):
if self.is_empty():
raise Exception("qu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.