content stringlengths 7 1.05M |
|---|
# 6. Zigzag Conversion
# Runtime: 103 ms, faster than 20.89% of Python3 online submissions for Zigzag Conversion.
# Memory Usage: 14.7 MB, less than 13.84% of Python3 online submissions for Zigzag Conversion.
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
re... |
#
# PySNMP MIB module AGENTX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGENTX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:15:42 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:... |
class Layer:
def __init(self):
self.input=None
self.output=None
def forward(self,input):
#to return the output layer
pass
def backward(self,output_gradient,learning_rate):
#change para and return input derivative
pass
|
class Capture:
def capture(self):
pass
|
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(input())
values = [str(f(x)) for x in range(0, n+1)]
print(",".join(values)) |
#TODO Create Functions for PMTA
## TORISPHERICAL TOP HEAD 2:1 - Min thickness allowed and PMTA
class TorisphericalCalcs:
def __init__(self):
self.L_top_head = None
self.r_top_head = None
self.ratio_L_r_top = None
self.M_factor_top_head = None
self.t_min_top_head = No... |
'''
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
In... |
# Collaborators (including web sites where you got help: (enter none if you didn't need help)
# claryse adams
def avg_temp(user_list):
total = 0
for x in range(1, len(user_list)):
total += user_list[x]
average = total/(len(user_list)-1)
average = round(average, 2)
return average
if __name... |
def fry():
print('The eggs have been fried')
|
class Data:
def __init__(self, dia, mes, ano):
self.dia = dia
self.mes = mes
self.ano = ano
print(self)
@classmethod
def de_string(cls, data_string):
dia, mes, ano = map(int, data_string.split("-"))
data = cls(dia, mes, ano)
return data
... |
"""
Created by adam on 5/20/18
"""
__author__ = 'adam'
class IModifierList(object):
"""
Interface for classes which act on a list of strings by modifying
the input strings and returning a list of modified strings.
Used for tasks like lemmatizing etc
"""
def __init__(self):
pass
d... |
class DummyContext:
context = {}
dummy_context = DummyContext()
|
#
# @lc app=leetcode id=783 lang=python3
#
# [783] Minimum Distance Between BST Nodes
#
# https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/
#
# algorithms
# Easy (51.05%)
# Likes: 524
# Dislikes: 157
# Total Accepted: 49.9K
# Total Submissions: 97K
# Testcase Example: '[4,2,6,1,3,null... |
class NameScope(object,INameScopeDictionary,INameScope,IDictionary[str,object],ICollection[KeyValuePair[str,object]],IEnumerable[KeyValuePair[str,object]],IEnumerable):
"""
Implements base WPF support for the System.Windows.Markup.INameScope methods that store or retrieve name-object mappings into a particular XAML... |
# Copyright 2020 BBC Research & Development
#
# 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 ... |
# -*- coding: utf-8 -*-
__author__ = 'Wael Ben Zid El Guebsi'
__email__ = 'benzid.wael@hotmail.fr'
__version__ = '0.0.0' |
# coding: utf-8
n = int(input())
li = [int(i) for i in input().split()]
print(sum(li)/n)
|
class Question:
def __init__(self, text, answer):
self.text = text
self.answer = answer
new_q = Question("lkajsdkf", "False")
|
#!/usr/bin/env python3
"""Mtools version."""
__version__ = '1.6.4-dev'
|
def buildMaskSplit(noiseGShape,
noiseGTexture,
categoryVectorDim,
attribKeysOrder,
attribShift,
keySplits=None,
mixedNoise=False):
r"""
Build a 8bits mask that split a full input latent vector int... |
def find_three_values_that_sum(lines, sum=2020):
for idx1, line1 in enumerate(lines):
for idx2, line2 in enumerate(lines[idx1:]):
for idx3, line3 in enumerate(lines[idx1+idx2:]):
num1 = int(line1)
num2 = int(line2)
num3 = int(line3)
... |
Invitados=[]
Invitados.append('Ciria Garcia')
Invitados.append('Esperanza Zul')
Invitados.append('Bryce Harper')
Msj="Me gustaria mucho que usted " + Invitados[0].title() + " pudiera acompañarme esta noche a cenar."
Msj1="Me encantaria poder compartir esta cena con mi abuela " + Invitados[1].title() + "."
Msj2="Seria ... |
class Constants(object):
"""
Constant declarations.
"""
API_URL = 'https://i.instagram.com/api/v1/'
VERSION = '9.2.0'
IG_SIG_KEY = '012a54f51c49aa8c5c322416ab1410909add32c966bbaa0fe3dc58ac43fd7ede'
EXPERIMENTS = 'ig_android_ad_holdout_16m5_universe,ig_android_progressive_jpeg,ig_creation_gro... |
"Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k"
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if not nums or len(nums) == 1:
return False
... |
class Solution:
def generate(self, numRows: int):
result = []
if not numRows:
return result
for i in range(1, numRows + 1):
temp = [1] * i
lo = 1
hi = i - 2
while lo <= hi:
temp[lo] = temp[hi] = result[i - 2... |
# @Title: 和为K的子数组 (Subarray Sum Equals K)
# @Author: KivenC
# @Date: 2018-07-19 18:00:52
# @Runtime: 84 ms
# @Memory: N/A
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# key为前n项的和,value为该和出现的次数
... |
"""
This problem was asked by Microsoft.
Given an array of numbers, find the length of the longest increasing subsequence in the array.
The subsequence does not necessarily have to be contiguous.
For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],
the longest increasing subsequence ha... |
class Empty(Exception):
pass
class LinkedQueue:
"""FIFO queue implkementation using a singly linked list for storage"""
class _Node:
"""Lightweight, nonpublic claass for storing a singly linked node."""
__slots__ = (
"_element",
"_next",
) # streamline me... |
# 1921. Eliminate Maximum Number of Monsters
# You are playing a video game where you are defending your city from a group of n monsters.
# You are given a 0-indexed integer array dist of size n, where dist[i] is the initial
# distance in meters of the ith monster from the city.
# The monsters walk toward the city at... |
__author__ = 'Chetan'
class Wizard():
def __init__(self, src, rootdir):
self.choices = []
self.rootdir = rootdir
self.src = src
def preferences(self, command):
self.choices.append(command)
def execute(self):
for choice in self.choices:
... |
#######################################################
#
# ManageRacacatPinController.py
# Python implementation of the Class ManageRacacatPinController
# Generated by Enterprise Architect
# Created on: 15-Apr-2020 4:57:23 PM
# Original author: Giu Platania
#
############################################... |
N = int(input())
ans = 0
if N < 10 ** 3:
print(0)
elif 10 ** 3 <= N < 10 ** 6:
print(N - 10 ** 3 + 1)
elif 10 ** 6 <= N < 10 ** 9:
print(10 ** 6 - 10 ** 3 + (N - 10 ** 6 + 1)*2)
elif 10 ** 9 <= N < 10 ** 12:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (N - 10 ** 9 + 1)*3)
elif 10 ** 12 <= N < 10 ... |
valor = 12
def teste_git(testes):
result = testes ** 33
return result
print(teste_git(valor))
|
def show_first(word):
print(word[0])
show_first("abc")
|
numero = int(input("Digite um número: "))
if ((numero % 5) == 0):
print("Buzz")
else:
print(numero)
|
def new_multiplayer(bot, message):
"""
/new_multiplayer command handler
"""
chat_id = message.chat.id
bot.send_message(chat_id=chat_id, text="Not implemented yet") |
def count_positives_sum_negatives(arr):
if not arr:
return []
positive_array_count = 0
negative_array_count = 0
neither_array = 0
for i in arr:
if i > 0:
positive_array_count = positive_array_count + 1
elif i == 0:
neither_array = neither_array + i
... |
input_shape = 56, 56, 3
num_class = 80
total_epoches = 50
batch_size = 64
train_num = 11650
val_num = 1254
iterations_per_epoch = train_num // batch_size + 1
test_iterations = val_num // batch_size + 1
weight_decay = 1e-3
label_smoothing = 0.1
'''
numeric characteristics
'''
mean = [154.64720717, 163.98750114, 1... |
def sort3(a, b, c):
i = []
i.append(a), i.append(b), i.append(c)
i = sorted(i)
return i
a, b, c = input(), input(), input()
print(*sort3(a, b, c))
|
'''
occurrences_dict
loop values:
occurrences_dict[value] += 1
'''
# numbers_string = '-2.5 4 3 -2.5 -5.54 4 3 3 -2.5 3'
# numbers_string = '2 4 4 5 5 2 3 3 4 4 3 3 4 3 5 3 2 5 4 3'
numbers_string = input()
occurrence_counts = {}
# No such thing as tuple comprehension, this is generator
numbers = [float(x) for x... |
count = 0
total = 0
while True:
Enter = input('Enter a number:\n')
try:
if Enter == "Done":
break
else:
inp = int(Enter)
total = total + inp
count = count + 1
average = total / count
except:
print('Invalid input')
print('Tot... |
#
# PySNMP MIB module BEGEMOT-IP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-IP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
SECRET_KEY = 'fake-key-here'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'd... |
# RUN: test-parser.sh %s
# RUN: test-output.sh %s
x = 1 # PARSER-LABEL:x = 1i
y = 2 # PARSER-NEXT:y = 2i
print("Start") # PARSER-NEXT:print("Start")
# OUTPUT-LABEL: Start
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if ... |
class CameraNotConnected(Exception):
pass
class WiredControlAlreadyEstablished(Exception):
pass
|
"""
Project Euler: Problem #002
"""
def solve(lim = 4 * 1000 * 1000):
"""
Naive solution with a function.
:param lim: Max number to sum up to.
:returns: The sum of the even Fibo-numbers.
"""
a, b = 0, 1
sum = 0
while b < lim:
if not b % 2:
sum +=... |
# https://codeforces.com/problemset/problem/116/A
n = int(input())
stops = [list(map(int, input().split())) for _ in range(n)]
p, peak_p = 0, 0
for stop in stops:
p -= stop[0]
p += stop[1]
peak_p = max(p, peak_p)
print(peak_p) |
def int_to_char(word):
arr = list(word)
num_str = ""
while True:
if not arr[0].isdigit():
break
num_str += arr[0]
arr.pop(0)
num = int(num_str)
arr.insert(0, chr(num))
return "".join(arr)
def switch_letters(word):
list_chars = list(word)
list_char... |
PROJECT_ID = 'dmp-y-tests'
DATASET_NAME = 'test_gpl'
BUCKET_NAME = 'bucket_gpl'
LOCAL_DIR_PATH = '/tmp/gpl_directory'
|
def print_inicia_jogo():
print("Bem-vindo ao jogo do NIM! Escolha:\n")
print("1 - para jogar uma partida isolada")
print("2 - para jogar um campeonato")
def vencedor(ganha_comp, ganha_usuario):
if ganha_comp:
return print("Fim do jogo! O computador ganhou!")
elif ganha_usuario:
retu... |
def commonDiv(num, den, divs = None) :
if not divs : divs = divisors(den)
for i in divs[1:] :
if not num % i : return True
return False
def validNums(den, minNum, maxNum) :
divs = divisors(den)
return [i for i in range(minNum,maxNum+1) if not commonDiv(i, den, divs)]
def countBetween(lowNum, lowDen, h... |
# Exception Handling function
def exception_handling(number1, number2, operator):
# Only digit exception
try:
int(number1)
except:
return "Error: Numbers must only contain digits."
try:
int(number2)
except:
return "Error: Numbers must only contain digits."
# More... |
TWITTER_TAGS = [
"agdq2021",
"gamesdonequick.com",
"agdq",
"sgdq",
"gamesdonequick",
"awesome games done quick",
"games done quick",
"summer games done quick",
"gdq",
]
TWITCH_CHANNEL = "gamesdonequick"
TWITCH_HOST = "irc.twitch.tv"
TWITCH_PORT = 6667
# Update this value to change t... |
'''
Problem : Find out duplicate number between 1 to N numbers.
- Find array sum
- Subtract sum of First (n-1) natural numbers from it to find the result.
Author : Alok Tripathi
'''
# Method to find duplicate in array
def findDuplicate(arr, n):
return sum(arr) - (((n - 1) * n) // 2) #it will return int no... |
#!/bin/python
def ParseCsv(csvFile, interval):
bytesList = []
framesList = []
ctn = 0
intervalCtr = 0
frameSun = 0
byteSun = 0
for i in range (0, 10*interval):
id, frames, bytes = csvFile[i].split(';')
frameSun += int(frames)
byteSun += int(bytes)
intervalCt... |
def get_score(player_deck):
score_sum=0
for i in player_deck:
try:
score_sum+=int(i[1])
except:
if i[1] in ['K', 'Q', 'J']:
score_sum+=10
if i[1]=='Ace':
if (score_sum+11)<=21:
score_sum+=11
... |
def ok(msg):
"""OK message
:msg: TODO
:returns: TODO
"""
return {"message": str(msg)}
def err(msg):
"""Error message
:msg: TODO
:returns: TODO
"""
return {"error": str(msg)}
|
#MenuTitle: Count Layer and Edit Note
# -*- coding: utf-8 -*-
# Edit by Tanukizamurai
__doc__="""
Count glyphs layers and add value to glyphs note.
"""
font = Glyphs.font
selectedLayers = font.selectedLayers
for thisLayer in selectedLayers:
thisGlyph = thisLayer.parent
layerCount = len(thisLayer.parent.layers) #c... |
class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
files = path.split('/')
stack = list()
for f in files:
if len(f) == 0 or f == '.':
continue
elif f == '..':
if len(stack):... |
# coding: utf-8
n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
if i < n-1 and a[i+1]<a[i]:
break
if i==n-1:
ans = 0
else:
ans = n-1-i
a = a[i+1:]+a[:i+1]
for i in range(n-1):
if a[i] > a[i+1]:
print(-1)
break
else:
print(ans)
|
# Scrapy settings for dirbot project
SPIDER_MODULES = ['dirbot.spiders']
NEWSPIDER_MODULE = 'dirbot.spiders'
DEFAULT_ITEM_CLASS = 'dirbot.items.Website'
ITEM_PIPELINES = {
'dirbot.pipelines.RequiredFieldsPipeline': 1,
'dirbot.pipelines.FilterWordsPipeline': 2,
'dirbot.pipelines.DbPipeline': 3,
}
# Databa... |
class Solution:
def getHeight(self, root):
if root is None:
return 0
lh = self.getHeight(root.left) + 1
rh = self.getHeight(root.right) + 1
return max(lh, rh)
def isBalanced(self, root):
if root is None:
return True
leftHeight = self.... |
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
# Dynamic programming, keep track of multiples of ugly 2s, 3s, and 5s
# Quick return
if n <= 0:
return 0
# Create dp array
dp = [1] * n
... |
# %%
#######################################
def merge_arrays(*lsts: list):
"""Merges all arrays into one flat list.
Examples:
>>> lst_abc = ['a','b','c']\n
>>> lst_123 = [1,2,3]\n
>>> lst_names = ['John','Alice','Bob']\n
>>> merge_arrays(lst_abc,lst_123,lst_names)\n
['a... |
def get_products_of_all_ints_except_at_index(int_list):
if len(int_list) < 2:
raise IndexError('Getting the product of numbers at other '
'indices requires at least 2 numbers')
# We make a list with the length of the input list to
# hold our products
products_of_all_in... |
count = 0 # A global count variable
def remember():
global count
count += 1 # Count this invocation
print(str(count))
remember()
remember()
remember()
remember()
remember()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 17:54:07 2019
@author: SaiLikhithK
"""
def merge_and_count(b,c):
res_arr, inv_count = [], 0
while len(b) > 0 or len(c) > 0:
if len(b) > 0 and len(c) > 0:
if b[0] < c[0]:
res_arr.append(b[0])
b = ... |
class IncapBlocked(ValueError):
"""
Base exception for exceptions in this module.
:param response: The response which was being processed when this error was raised.
:type response: requests.Response
:param *args: Additional arguments to pass to :class:`ValueError`.
"""
def __init__(self, r... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: median.py
@time: 2019/6/15 14:18
@desc:
'''
class Solution:
"""
@param A: An integer array.
@param B: An integer array.
@return: a double whose format is *.5 or... |
def find_rc(rc):
rc = rc[:: -1]
replacements = {"A": "T",
"T": "A",
"G": "C",
"C": "G"}
rc = "".join([replacements.get(c, c) for c in rc])
return rc
print(find_rc('ATTA'))
|
"""Configuration settings for baseball team manager program."""
# The starting players list of lists
players = [
['Joe', 'P', 10, 2, 0.2],
['Tom', 'SS', 11, 4, 0.364],
['Ben', '3B', 0, 0, 0.0],
]
# valid baseball team positions
valid_positions = ('C', '1B', '2B', '3B', 'SS', 'LF'... |
first_name = input("Please enter your first name: ")
print(f"Your first name is: {first_name}")
print("a regular string: " + first_name)
print('a regular string' + first_name)
# string literal with the r prefix
print(r'a regular string')
|
"""
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
"""
class Solution:
# @param A, a... |
# A variable lets you save some information to use later
# You can save numbers!
my_var = 1
print(my_var)
# Or strings!
my_var = "MARIO"
print(my_var)
# Or anything else you need! |
def code_to_color(code):
assert len(code) in (4, 5, 7, 9), f'Bad format color code: {code}'
if len(code) == 4 or len(code) == 5: # "#RGB" or "#RGBA"
return tuple(map(lambda x: int(x, 16) * 17, code[1:]))
elif len(code) == 7 or len(code) == 9: # "#RRGGBB" or "#RRGGBBAA"
return tuple(map(la... |
class Payload:
@staticmethod
def login_payload(username, password):
return {'UserName': username, 'Password': password, 'ValidateUser': '1', 'dbKeyAuth': 'JusticePA',
'SignOn': 'Sign+On'}
@staticmethod
def payload(param_parser, last_name, first_name, middle_name, birth_date):
... |
class Solution:
def addBinary(self, a: str, b: str) -> str:
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
result = ''
# initialize the carry
carry = 0
# Traverse the string
for i in range(max_len - 1, -1, -1):
r... |
'''
Locating suspicious data
You will now inspect the suspect record by locating the offending row.
You will see that, according to the data, Joyce Chepchumba was a man that won a medal in a women's event. That is a data error as you can confirm with a web search.
INSTRUCTIONS
70XP
Create a Boolean Series with a con... |
class InvalidSymbolException(Exception):
pass
class InvalidMoveException(Exception):
pass
class InvalidCoordinateInputException(Exception):
pass
|
def odd_nums(number: int) -> int:
for num in range(1, number + 1, 2):
yield num
pass
n = 15
generator = odd_nums(n)
for _ in range(1, n + 1, 2):
print(next(generator))
next(generator)
|
def find_nemo(array):
for item in array:
if item == 'nemo':
print('found NEMO')
nemo = ['nemo']
find_nemo(nemo) |
def loss_function(X_values, X_media, X_org):
# X_media = {
# "labels": ["facebook", "tiktok"],
# "coefs": [6.454, 1.545],
# "drs": [0.6, 0.7]
# }
# X_org = {
# "labels": ["const"],
# "coefs": [-27.5],
# "values": [1]
# }
y = 0
for i in range(len(X_values)):
... |
"""map() and filter():
('list' only a literal list if you call list over it)
map(func, list) -> Returns 'list' with func applied to items.
strings = map(str, [hello, world])
strings == ['hello', 'world']
filter(func, list) -> Returns 'list' of items that func already applies to.
even = filter(lambda n: n % 2, [3, ... |
def getcommonletters(strlist):
return ''.join([x[0] for x in zip(*strlist) \
if reduce(lambda a,b:(a == b) and a or None,x)])
def findcommonstart(strlist):
strlist = strlist[:]
prev = None
while True:
common = getcommonletters(strlist)
if common == prev:
... |
# DO NOT comment out
# (REQ) REQUIRED
# *****************************************************************************
# DATA DISCOVERY ENGINE - MAIN (REQ)
# *****************************************************************************
# name also used on metadata
SITE_NAME = "NIAID Data Portal"
SITE_DESC = 'An aggr... |
# pylint: skip-file
POKEAPI_POKEMON_LIST_EXAMPLE = {
"count": 949,
"previous": None,
"results": [
{
"url": "https://pokeapi.co/api/v2/pokemon/21/",
"name": "spearow"
},
{
"url": "https://pokeapi.co/api/v2/pokemon/22/",
"name": "fearow"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def __update(self, iterable):
for item in iterable:
self.items_list.append(item)
def test_parent(self):
print(self.__update... |
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
length = len(nums)
while i < length:
if nums[i] == val:
nums[i:] = nums[i + 1:]
length -= 1
else:
i += 1
return length
|
# 7x^1 - 2x^2 + 1x^3 + 2x^4 = 3
# 2x^1 + 8x^2 + 3x^3 + 1x^4 = -2
# -1x^1 + 0x^2 + 5x^3 + 2x^4 = 5
# 0x^1 + 2x^2 - 1x^3 + 4x^4 = 4
def getX1(x2,x3,x4):
return (3+2*x2-x3-2*x4)/7
def getX2(x1,x3,x4):
return (-2-2*x1-3*x3-x4)/8
def getX3(x1,x2,x4):
return (5+x1-2*x4)/5
def getX4(x1,x2,x3):
return... |
def calc_fact(num):
total = 0
final_tot = 1
for x in range(num):
total = final_tot * (x+1)
final_tot = total
print(total)
calc_fact(10) # excepted output: 3628800 |
# criando função sem print e sem return
def erro(x=10, y=10):
x+y
print(erro()) |
"""
Напишите рекурсивную функцию sum(a, b), возвращающую сумму двух целых неотрицательных чисел. Из всех
арифметических операций допускаются только +1 и -1. Также нельзя использовать циклы.
Формат ввода
Вводятся два удовлетворяющих условию задачи числа. Числа не превышают 900.
Формат вывода
Выведите ответ на задачу.
... |
idade = int(input('Digite sua idade: '))
sexo = str(input('Digite o sexo M ou F: ')).upper()
#if idade > 18:
# print('Você já tem que pagar suas contas')
#elif idade == 18:
# print('Vai começar a se fuder agora')
#else:
# print('Pode deixar que os seus Pais pagam a conta.')
if sexo == 'M':
if idade >= 18... |
z = int(input())
y = int(input())
x = int(input())
space = x * y * z
box = int(0)
box_space = int(0)
while box != "Done":
box = input()
if box != "Done":
box = float(box)
box = int(box)
box_space += box
if box_space > space:
print(f"No more free space! You need {box_space - s... |
DEBUG_MODE = False
#DIR_BASE = '/tmp/sms'
DIR_BASE = '/var/spool/sms'
DIR_INCOMING = 'incoming'
DIR_OUTGOING = 'outgoing'
DIR_CHECKED = 'checked'
DIR_FAILED = 'failed'
DIR_SENT = 'sent'
# Default international phone code
DEFAULT_CODE = '62'
# Unformatted messages will forward to
FORWARD_TO ... |
#===============================================================
# DMXIS Macro (c) 2010 db audioware limited
#===============================================================
sel = GetAllSelCh(False)
if len(sel)>0:
for ch in sel:
RemoveFixture(ch) |
class Solution(object):
def getRow(self, rowIndex):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if rowIndex == 0:
return [1]
if rowIndex == 1:
return [1, 1]
r = [1, 1]
for n in range(2, rowIndex + 1):
row = []... |
#!/usr/bin/python3
def echo(input):
return input
def count_valid(data, anagrams=True):
valid = 0
if anagrams:
sort = echo
else:
sort = sorted
for line in data:
words = []
for word in line.split():
if sort(word) not in words:
words.appen... |
def initialize():
global detected, undetected, unsupported, total, report_id
detected = {}
undetected = {}
unsupported = {}
total = {}
report_id = {}
def initialize_colours():
global HEADER, OKBLUE, OKCYAN, OKGREEN, WARNING, FAIL, ENDC, BOLD, UNDERLINE, ALERT, GRAY, WHITE, END
global C... |
"""
Problem 2_1:
Write a function 'problem2_1()' that sets a variable lis = list(range(20,30)) and
does all of the following, each on a separate line:
(a) print the element of lis with the index 3
(b) print lis itself
(c) write a 'for' loop that prints out every element of lis. Recall that
len() will give you the l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.