content stringlengths 7 1.05M |
|---|
#Prints the number in matrix form
def print_numbers(number):
for i in range(1,number+1):
for j in range(1, number+1):
print(i,end=" ")
print()
number=int(input("please enter a number: "))
if number%2==0:
print_numbers(number+1)
else:
print_numbers(number-1)
|
class Blackjack():
def __init__(self, cards):
self.cards = cards
def hand(self):
"""makes a list of your card values
Returns:
list: e.g. [1, 12]
"""
deck = {
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
... |
def bar_spec(data):
return {
"config": {
"view": {"continuousWidth": 400, "continuousHeight": 300},
"mark": {"opacity": 0.75}
},
"layer": [
{
"mark": {"type": "bar", "color": "red"},
"encoding": {
"x": {... |
#!/usr/bin/env python
#
# Copyright (C) 2017 ShadowMan
#
class FatalError(Exception):
pass
class FrameHeaderParseError(Exception):
pass
class ConnectClosed(Exception):
pass
class RequestError(Exception):
pass
class LoggerWarning(RuntimeWarning):
pass
class DeamonError(Exception):
pass... |
#!/usr/bin/env python
#coding: utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
h = ch = ListNode(-1)
n1, n2, c = l1, l2, 0
... |
def is_uppercase(letter: str):
return True if 65 <= ord(letter) <= 90 else False
def is_lowercase(letter: str):
return True if 97 <= ord(letter) <= 122 else False
def check_same_case(first: str, second: str) -> bool:
if is_uppercase(first) and is_uppercase(second):
return True
if is_lowerca... |
# ========================= VMWriter CLASS
class VMEncoder(object):
"""
VM encoder for the CompilationEngine of the Jack compiler.
"""
def encodePush(self, segment, index):
"""
Creates VM push command based on the input.
args:
segment: (str) segment to operate on
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
listL1, listL... |
msg = str(input('Digite algo: '))
print(f'O tipo primitivo dele é {type(msg)}')
print(f'So tem espaços? ', msg.isspace())
print(f'É um número? ', msg.isnumeric())
print(f'É alfabetico? ', msg.isalpha())
print(f'É alfanúmerico? ', msg.isalnum())
print(f'Está em maisculas? ', msg.isupper())
print(f'Está em minuscolas? ',... |
""" z-matrix writers
"""
def write(syms, key_mat, name_mat, val_dct, mat_delim=' ', setval_sign='='):
""" write a z-matrix to a string
"""
mat_str = matrix_block(syms=syms, key_mat=key_mat, name_mat=name_mat,
delim=mat_delim)
setval_str = setval_block(val_dct=val_dct, setval... |
n=int(input("enter a number"))
m=int(input("enter a number"))
if n%m==0:
print(n,"is dividible by",m)
else:
print(n,"is not divisible by",m)
if n%2==0:
print(n,"is even")
else:
print(n,"is odd")
|
"""Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
"""
class Solution(object):
def addDigits(self, num):
while num >= 10:
num =... |
file_extractors = {}
def file_extractor(extension):
"""
This decorator registers functions to be used as extractors.
Only functions decorated with this are considered metadata extractors, and will
be called when the file extension matches the configured one.
:param extension: the extension to ma... |
MAX = 'x'
MIN = 'o'
def get_player(s):
return MAX if len([1 for i in s if i == ' ']) % 2 == 1 else MIN
def next_player(p):
return MAX if p == MIN else MIN
def get_actions(s):
return [i for i in range(9) if s[i] == ' ']
def result(s, a):
player = get_player(s)
s2 = list(s)
s2[a] = player
... |
# What are the factors of 18?
# factor: an integer which when multiplied with another integer, results in the product 18.
# Hence when 18 is divided by this number, the dividend is an integer and there are no remainders.
num = 18
for i in range(1, num+1):
if num % i == 0:
print(i, end=' ')
|
def main():
for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().strip().split()))
if n == 1:
print(arr[0])
else:
n += 1
arr.append(1001)
left, right = 0, 1
res = ''
while left <= right and ... |
#########################################################################################
# IMPORTANT: This file should be copied to setting.py and then completed before use #
#########################################################################################
# Rocky Version
VERSION = '0.3.5'
# Path to js... |
###########################################################
# #
# Solving factorial problem with recursive function #
# #
###########################################################
def factorial(n):
... |
"""Enter n, use the recursion method (for example,
derive the latter term from the relationship between the preceding items,
it is a one-loop question) and caculate the sum of 1+2!+3!+...+n! and output the result."""
n = int(input('Give me a integer: '))
s = term = 1
for i in range(2, n+1):
term *= i
s += t... |
cont = soma = media = maior = menor = 0
res = 'S'
while res == 'S':
num = int(input('Digite um número: '))
res = str(input('Quer continuar? [S/N] ').strip().upper())
soma += num
cont += 1
if cont == 1:
maior = menor = num
else:
if maior < num:
maior = num
if m... |
"""
23 - Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos
dígitos separados.
Ex: Digite um número: 1834
unidade: 4
dezena: 3
centena: 8
milhar: 1
"""
num = int(input('Informe um número: '))
print('=*='*10)
print(f'\033[33mAnalisando o número {num}\033[m')
print('=*='*10)
print(f'Unidade: \03... |
# -*- coding: utf-8 -*-
"""
1417. Reformat The String
Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit
is followed by another digit. That is, no two... |
# coding=utf-8
'''
Created on 2017年11月25日
@author: jianpinh
'''
eng_10jqka_CookieList = [
'AcL0X6qrL2k4wjM1rx64KE2PFcMhk8ameJe60Qzb7jXgX2x39CMWvUgnCuXc',
'AQI0H2rr7yl4gvABCen4aA1PVQNh0wayuNf6B0wbLnUgn6y3NGNW_YhnSiUc',
'AR0rznlCGEhb2_-QOepvqU4GKvISOlGMW261YN_iWXSjljNmp4phXOu-xTlv',
'AePVMIOgvj4xWXH-c8aJ... |
#
# University of Luxembourg
# Laboratory of Algorithmics, Cryptology and Security (LACS)
#
# FigureOfMerit (FOM)
#
# Copyright (C) 2015 University of Luxembourg
#
# Written in 2015 by Daniel Dinu <dumitru-daniel.dinu@uni.lu>
#
# This file is part of FigureOfMerit.
#
# This program is free software; you can redistribut... |
__all__ = (
'ESputnikException',
'InvalidAuthDataError',
'IncorrectDataError'
)
class ESputnikException(AttributeError):
pass
class InvalidAuthDataError(ESputnikException):
def __init__(self, code, message):
self.code = code
self.message = message
class IncorrectDataError(Inval... |
class TextFieldFsm:
def __init__(self, title, position, need_hide=False, initial_text=""):
self.title = title
self.position = position
self.need_hide = need_hide
self.initial_text = initial_text
|
BINDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/bin'
DATADIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share'
DATAROOTDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share'
DESTDIR ... |
"""
Avoiding Syntax Errors with Strings
Here’s how to use single and double quotes correctly.
"""
message = "One of Python's strengths is its diverse community."
print(message)
"""
split line for each point
"""
print("------------------------------split line------------------------------")
'''
However, if you u... |
wanted_profit = float(input())
is_wanted_profit_gained = False
total_amount = 0
cocktail = input()
while cocktail != 'Party!':
number_of_cocktails = int(input())
cocktail_price = len(cocktail)
order_price = cocktail_price * number_of_cocktails
if order_price % 2 != 0:
order_price = order_price ... |
'''
Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida:
- Média abaixo de 5.0: REPROVADO
- Média entre 5.0 e 6.9: RECUPERAÇÃO
- Média 7.0 ou superior: APROVADO
'''
titulo = str( 'MÉDIA FINAL' )
centralizar = str( ' ' * int( ((60 - len(t... |
# Define a class to receive the characteristics of each line detection
class Line():
def __init__(self):
# was the line detected in the last iteration?
self.detected = False
# x values of the last n fits of the line
self.recent_xfitted = []
#average x values of the fitted ... |
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_nunit3_test", "core_resource")
COMMON_DEFINES = [
"NETSTANDARD2_0",
"NETCOREAPP2_0",
"SERIALIZATION",
"ASYNC",
#"PLATFORM_DETECTION",
"PARALLEL",
"TASK_PARALLEL_LIBRARY_API",
]
core_library(
name = "nunit.framework.d... |
"""
给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例:
输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
说明:
可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
你算法的时间复杂度应该为 O(n2) 。
进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-increasing-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
... |
# Strings Part-1 - Definition,casting and indexing
my_string = "Python101!"
another_string = 'Welcome '
# quoting the quote !
dialog = 'He asked , "But sir, python is a snake?!" '
reply = "Monty replied , 'Of course it is.' "
multi_line = """ You cans freely type here , without worrying about
using \n to go on to a n... |
"""
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-... |
"""
Given two sorted linked lists, merge them so that the resulting linked list is also sorted.
Consider two sorted linked lists and the merged list below them as an example. Click here to view the solution in C++, Java, JavaScript, and Ruby.
head1 -> 4 -> 8 -> 15 -> 19 -> null
head2 -> 7 -> 9 -> 10 -> 16 -> null
hea... |
def solution(l):
parsed = [e.split(".") for e in l]
toSort = [map(int, e) for e in parsed]
sortedINTs = sorted(toSort)
sortedJoined = [('.'.join(str(ee) for ee in e)) for e in sortedINTs]
return sortedJoined |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == '__main__':
print("************************************************************************")
print("* WELCOME TO ZEROMCMP (OpenSource MultiCloud Management Platform) *")
print("**************************************************************... |
class Settings:
def __init__(self):
self.screen_width = 900
self.screen_height = 700
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 1
# bullet
self.bullet_speed_factor = 1
self.bullet_width = 4
self.bullet_height = 4
self.bullet_color... |
def main() -> None:
S = input()
print("Yes" if "AC" in [S[i:i+2] for i in range(len(S)-1)] else "No")
if __name__ == '__main__':
main()
|
i= 1
while i<=3:
print("Guess:", i)
i=i+1
print("sorry you failed") |
config = {
# application info
'name': "texfuuin", # navbar application name
'db_path': "./texfuuin-db.json", # path to tinydb file
'port': 5000, # port to listen in production mod... |
src = Split('''
aos/soc_impl.c
hal/uart.c
hal/flash.c
main.c
''')
deps = Split('''
kernel/rhino
platform/arch/arm/armv7m
platform/mcu/wm_w600/
kernel/vcall
kernel/init
''')
global_macro = Split('''
STDIO_UART=0
CONFIG_NO_TCPIP
... |
# Test helper functions and classes
class ParameterPassLevel:
FLAG = 0
INI_KEY = 1
MARKER = 2
def _assert_result_outcomes(
result, passed=0, skipped=0, failed=0, error=0, dynamic_rerun=0
):
outcomes = result.parseoutcomes()
_check_outcome_field(outcomes, "passed", passed)
_check_outcome_... |
# O(1) time | O(1) space
def validIPAddresses(string):
ipAddressesFound = []
for i in range(1, min(len(string), 4)): # from index 0 - 4
currentIPAddressParts = ["","","",""]
currentIPAddressParts[0] = string[:i] # before the first period
if not isValidPart(currentIPAddressParts[0]):
continue
for j... |
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
# TODO: 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
# django-oauth-toolkit >= 1.0.0
# 'rest_framework_social_oauth2.authentication.SocialAuthenticati... |
def is_merge(s, part1, part2):
all_chars = len(s) == len(part1) + len(part2)
if not all_chars:
return False
d = {}
for i, c in enumerate(s):
d[c] = i
indices1, indices2 = [d[c] for c in part1], [d[c] for c in part2]
part1_good = indices1 == sorted(indices1)
part2_good = indic... |
def Duplicate_Charaters(Test_String):
Duplicates = []
for char in Test_String:
if Test_String.count(char) > 1 and char not in Duplicates:
Duplicates.append(char)
return Duplicates
Test_String = input("Enter a String: ")
print(*(Duplicate_Charaters(Test_String)))
|
#!python3
def main():
with open('21.txt', 'r') as f, open('21_out.txt', 'w') as f_out:
lines = f.readlines()
# Part 1
answer = 0
print(answer)
print(answer, file=f_out)
# Part 2
print(answer)
print(answer, file=f_out)
if __name__ == '__main__':
... |
class HashState:
def __init__(self, player, cards, leading, upper, lower, tricks):
self.current_player = player
self.cards = cards
self.upper_bound = upper
self.lower_bound = lower
self.leading_suite = leading
self.tricks_left = tricks
def get_current_player(... |
# -*- coding: utf-8 -*-
# License: See LICENSE file.
required_states = ['position']
required_matrices = ['cellular_binary_grass']
def run(name, world, matrices, states, extra_life=10):
y,x = states['position']
#if matrices['cellular_binary_grass'][int(y),int(x)]:
# Eat the cell under the agent's position... |
class Config:
def __init__(self, classified_types: [str]):
self.classified_types = classified_types
|
nterms = int(input("Stevilo cifr? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Vnesi pozitivno stevilo: ")
elif nterms == 1:
print("Sekvenca do ",nterms,": ")
print(n1)
else:
print("Sekvenca:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
coun... |
# -*- coding: utf-8 -*-
# Kurs: Python: Grundlagen der Programmierung für Nicht-Informatiker
# Semester: Herbstsemester 2018
# Homepage: http://accaputo.ch/kurs/python-uzh-hs-2018/
# Author: Giuseppe Accaputo
# Aufgabe: 2.1
def summe(a,b,c):
print(a + b + c)
summe(1,2,3)
summe(1,-1,0)
s... |
#Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80kmH, mostre uma messagem
#dizendo que ele foi mutado. A multa vai custar R$7,00 por cada Km acima do limite.
vel = float(input('Qual é a velocidade atual do carro? '))
if vel > 80:
print('MULTADO! Você excedeu o limite permitido que é de 8... |
issues=[
dict(name='Habit',number=5,season='Winter 2012',
description='commit to a change, experience it, and record'),
dict(name='Interview', number=4, season='Autumn 2011',
description="this is your opportunity to inhabit another's mind"),
dict(name= 'Digital Presence', number= 3, season= ... |
def bestSum(t, arr, memo=None):
"""
m: target sum, t
n: len(arr)
time = O(n^m*m)
space = O(m*m) [in each stack frame, I am storing an array, which in worst case would be m]
// Memoized complexity
time = O(n*m*m)
space = O(m*m)
"""
if memo is None:
memo = {}
if t in memo:
return memo[t]
if t == 0:
r... |
"""Expectations that can be placed on an HTTP request"""
class ResponseExpectation(object):
"""An expectation placed on an HTTP response."""
def __init__(self):
pass
def validate(self, validation, response):
"""If the expectation is met, do nothing. If the expectation is
not met... |
num = 1
factors = list()
while num <= 100:
if (num % 10) == 0:
factors.append(num)
num = num + 1
print("Factors :",factors)
|
#! /usr/bin/env python3
"""
Print patterns based on Pascal's Triangle.
"""
class Triangle:
"""Represents a Pascal's Triangle which can be rendered as text.
"""
def __init__(self, num_rows):
self.num_rows = num_rows
self.rows = [[1]]
prev_row = [1]
for row_num in range(1, n... |
dict(
source=["/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.diag.shuf.h5"],
target=["/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.drug.shuf.h5"],
indx_word="/home/yzhang3151/project/NMT/experiments/nmt/ivocab.diag.pkl",
indx_word_target="/home/yzhang3151/project/NMT/experiments/nmt/ivocab.... |
# ********************************************************************
# THE RED ACT
# rOsita fu
# 06-23-2020
# github.com/atisor73
# ********************************************************************
save = True
def setup():
size(500, 700)
frameRate(10)
rows, cols = 15, 15
num_squares = rows*cols
t = [ran... |
# Faça um programa que leia um número inteiro qualquer e mostre na tela a sua tabuada. #
num = int(input('Digite um numero: '))
print(f'{num} x {1} = ', num * 1)
print(f'{num} x {2} = ', num * 2)
print(f'{num} x {3} = ', num * 3)
print(f'{num} x {4} = ', num * 4)
print(f'{num} x {5} = ', num * 5)
print(f'{num}... |
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic list exercises
# Fill in the code for the functions below. main() is already set ... |
"""
10171 : 고양이
URL : https://www.acmicpc.net/problem/10171
Input :
Output :
\ /\
) ( ')
( / )
\(__)|
"""
print("\\ /\\")
print(" ) ( ')")
print("( / )")
print(" \\(__)|")
|
#HERE IS WHERE YOU CHANGE THE URL TO YOUR MOODLE SERVER
#MAKE SURE ALL THE PHP FILES ARE IN THE API FOLDER FOR THIS TO WORK
#CAN CHANGE THE API KEY HERE AS WELL
loginAPIcall = 'http://157.245.126.159/api/login.php'
getPointsAPIcall = 'http://157.245.126.159/api/get_user_points.php'
removePointsAPIcall = 'http://157.24... |
#
# PySNMP MIB module DELL-NETWORKING-FIB-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DELL-NETWORKING-FIB-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:37:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
elif l2 is None:
return l... |
class AuthNError(Exception):
"""AuthN is missing something. Either URL and/or API Keys
Args:
Exception ([type]): [description]
"""
pass
|
def fib(n):
f1 = 1
f2 = 2
s = 2
while f2 < n:
nxt = f1 + f2
f1 = f2
f2 = nxt
if nxt & 1 == 0:
s += nxt
return s
print(fib(4000000))
|
num1=100
num2=200
num3=300
|
def recherche_dichotomique(tableau, element):
return _recherche_dichotomique(tableau, element, 0, len(tableau) - 1)
def _recherche_dichotomique(tableau, element, premier, dernier):
'''recherche_dichotomique (list(object) * object * int * int-> int) :
renvoie l'indice de l'élément dans le tableau préalablem... |
class FieldType:
def __init__(self):
pass
Invalid = 0
Integer = 1
Text = 2
Note = 3
DateTime = 4
Counter = 5
Choice = 6
Lookup = 7
Boolean = 8
Number = 9
Currency = 10
URL = 11
Computed = 12
Threading = 13
Guid = 14
MultiChoice = 15
GridCh... |
'''Challenges Set 1 Challenge 3 Single-byte XOR cipher'''
# http://www.data-compression.com/english.html
CHARACTER_FREQ = {
'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.0158610,
'h': 0.0492888, 'i': 0.0558094, 'j': 0.0009033, 'k': 0.0050529, 'l':... |
#!/usr/bin/env python3
# -*- coding=utf-8 -*-
# 注意:
# input()返回的是字符串
# 必须通过int()将字符串转换为整数
# 才能用于数值比较:
age = int(input('请输入你的年龄:'))
if age >= 18:
print("成年人")
elif age >= 6:
print("青少年")
else:
print('孩子')
|
bids_schema = {
# BIDS identification bits
'modality': {
'type': 'string',
'required': True
},
'subject_id': {
'type': 'string',
'required': True
},
'session_id': {'type': 'string'},
'run_id': {'type': 'string'},
'acq_id': {'type': 'string'},
'task_id... |
# prime.py
# coding: utf-8
def primeList(num):
"""エラトステネスの篩を使ってn以下の素数リストを返す"""
if num<1:
return []
tmp=range(num+1)
tmp[0],tmp[1]=False,False
primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
for i in xrange(len(primes)):
if... |
class Adder:
'''
This class of functions contains all the additional functions required to add the website components.
'''
def __init__(self):
pass
def addBlogsL1(self, index_file: str) -> str:
'''
Function to add blogs section and meta text (comment) needed for blogpost ... |
# https://blog.csdn.net/l153097889/article/details/48310739
class TreeNode:
def __init__(self, value=None, leftNode=None, rightNode=None):
self.value = value
self.leftNode = leftNode
self.rightNode = rightNode
class Tree:
def __init__(self, root=None):
self.root = root
def... |
# Python - 2.7.6
class Ship:
def __init__(self, draft, crew):
self.draft = draft
self.crew = crew
def is_worth_it(self):
return (self.draft - self.crew * 1.5) > 20
|
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# 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 la... |
def is_palindrome(word: str) -> bool:
word = word.replace(' ','').lower() #Take out every space and convert to lowercase the entire string
assert len(word) > 0 , 'Error: Cannot process empty words'
return word == word[::-1]
def main():
word: str = input('Write a word: ')
if is_palindrome(word):
... |
# Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
# And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
|
frogs = input().split()
while True:
line = input()
tokens = line.split()
command = tokens[0]
if command == 'Join':
name = tokens[1]
frogs.append(name)
elif command == 'Jump':
name = tokens[1]
index = int(tokens[2])
if 0 <= index < len(frogs):
... |
print('===== DESAFIO 065 =====')
op = ''
count = 0
media = 0
maior = menor = 0
while op != 'n':
num = int(input('digite um valor: '))
count += 1
media += num
if count == 1:
maior = num
menor = num
else:
if num > maior:
maior = num
if num < menor:
... |
# 🚨 Don't change the code below 👇
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#My Solution
print(int(float(weight)/(float(height)*float(height))))
#Facit
bmi = int(weight) / float(height)**2
print(i... |
def max_sub_array_of_size_k(k, arr):
# TODO: Write your code here
if not arr:
return -1
curSum = 0
i = 0
j = len(arr) -1
while i < j:
subarr = arr[i:k]
print(subarr)
total = 0
for num in subarr:
total += num
if total > curSum:
... |
# DESAFIO 1
'''nome = input('Qual o seu nome?')
print('Olá', nome, '! Sejá bem-vinde!')'''
# DESAFIO 2
'''dia = input('Dia: ')
mes = input('Mês: ')
ano = input('Ano: ')
print('Você nasceu no dia:' , dia , 'de' , mes , 'de' , ano , '. Certo?')'''
# DESAFIO 3
''' Precisa especificar tipo primitivo.
num1 = input('1º ... |
template = "#include \"kernel.h\"\n#include \"ecrobot_interface.h\"\n@@BALANCER@@\n@@VARIABLES@@\n\nvoid ecrobot_device_initialize(void)\n{\n@@INITHOOKS@@\n}\n\nvoid ecrobot_device_terminate(void)\n{\n@@TERMINATEHOOKS@@\n}\n\n/* nxtOSEK hook to be invoked from an ISR in category 2 */\nvoid user_1ms_isr_type2(void){ /* ... |
# Time: O(n^2 * 2^n)
# Space: O(1)
# brute force, bitmask
class Solution(object):
def maximumGood(self, statements):
"""
:type statements: List[List[int]]
:rtype: int
"""
def check(mask):
return all(((mask>>j)&1) == statements[i][j]
for i ... |
# coding: utf-8
""" 一些语言相关的接口
"""
class Parser(object):
def __init__(self, preps=""):
self.prep_strs = preps.split('!')
self.preps = []
self.setup_prep()
def setup_prep(self):
pass
def parse(self, path):
""" parse
"""
raise NotImplementedError()
... |
# Leia um valor de áreas em acres e apresente-o convertido em m².
# A formula de conversão é: M = A * 4048.58
A = float(input("Digite um valor em acres: "))
M = A * 4048.58
print(f"O valor em acres para m² é: {M}")
|
string = "Hello world"
for char in string:
print(char)
length = len(string)
print(length)
|
expected_output = {
'vrf': {
'HIPTV': {
'address_family': {
'ipv4': {
'routes': {
'172.25.254.37/32': {
'known_via': 'bgp 7992',
'ip': '172.25.254.3... |
class Search:
def __init__(self):
pass
def execute(self):
pass
def __repr__(self):
pass
def __str__(self):
pass
class QueryBuilder:
pass
class Query:
pass
|
def double_exponential_smoothing(series, initial_level, initial_trend,
level_smoothing, trend_smoothing):
"""
Fit the trend and level to the timeseries using double exponential smoothing
Args:
- series: series, time-series to perform double exponential smoothing on
... |
'''
You are given an integer n, the number of teams in a tournament
that has strange rules:
- If the current number of teams is even, each team gets
paired with another team. A total of n / 2 matches are
played, and n / 2 teams advance to the next round.
- If the current ... |
# The purpose of __all__ is to define the public API of this module, and which
# objects are imported if we call "from {{ cookiecutter.project_name }}.hello import *"
__all__ = [
"HelloClass",
"say_hello_lots",
]
class HelloClass:
"""A class whose only purpose in life is to say hello"""
def __init__(... |
"""This problem was asked by Quora.
Given an absolute pathname that may have . or .. as part of it,
return the shortest standardized path.
For example, given "/usr/bin/../bin/./scripts/../", return "/usr/bin/".
""" |
def day23P1():
pullzle = "463528179"
#pullzle = "389125467"
cups = [int(x) for x in list(pullzle)]
l = len(cups)
startIdx = 0
for i in range(100):
p1 = (startIdx + 1) % l
p2 = (startIdx + 2) % l
p3 = (startIdx + 3) % l
p4 = (startIdx + 4) % l
pickup = [cu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.