content stringlengths 7 1.05M |
|---|
'''
4) Modifique o problema anterior para determinar
também o valor inteiro mínimo da sequência de
números fornecidos pelo usuário.
'''
entradas = (int(input("Total de entradas a serem fornecidas: "))) # Quantidade de números a serem lidos
i = 1
min = True
'''
Esta variável acima vai conter o valor menor. A princípio... |
N = int(input())
K = int(input())
M = int(input())
def mul(m1, m2):
m = [[0,0],[0,0]]
for i in range(0,2):
for j in range(0,2):
for k in range(0,2):
m[i][j] = m[i][j]+m1[i][k]*m2[k][j]
m[i][j] = m[i][j] % M
return m
def mpow(m, p):
res = [[... |
# ### Problem 5
# Create a SportsTeam Class for tracking sports teams. The class should have the properties team_name_p, team_city, and team_ranking_p.
class SportsTeam:
def __init__(self, team_name_p, team_city, team_ranking_p):
self.team_name_p = team_name_p
self.team_city = team_city
sel... |
"""
585. Maximum Number in Mountain Sequence
"""
class Solution:
"""
@param nums: a mountain sequence which increase firstly and then decrease
@return: then mountain top
"""
def mountainSequence(self, nums):
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = star... |
"""
@Pedro Santana Abreu (https://linktr.ee/pedrosantanaabreu)
@Curso em Vídeo (https://cursoemvideo.com)
PT-BR:
Faça um programa que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas.
"""
# Recebendo variável nome
nome = input('Digite seu nome: ')
# Exibindo mensagem de boas-vindas
print('É um prazer t... |
# Copyright 2019 Nicole Borrelli
#
# 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... |
# options
NO = 0
YES = 1
def translate_option(options):
option_list = []
for option in options:
option_list.append((option[0], option[1]))
return option_list
yes_no_options = translate_option([("No", NO), ("Yes", YES)])
|
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return n
else:
return self.climbStairs(n-1) + self.climbStairs(n-2)
s = Solution()
print(s.climbStairs(3)) |
class Person:
"人类"
def __init__(self, name, age, weight, height):
self.name = name
self.age = age
self.weight = weight
self.height = height
def showMysef(self):
print(self.name + " " + str(self.age) + " years old, " +
str(self.weight) + "kg, " + str(se... |
"""Validation services"""
def validate_obligate_fields(fields: any = None):
"""Validate if a list of obligate params are valid
:param fields: object that contains all params that are obligate,
these values can be arrays or simple values."""
'''You can use the following example:
_validate = ... |
# Default url patters for the engine.
urlpatterns = []
|
"""
Smallest Difference:
Write a function that takes in two non-empty arrays of integers,
finds the pair of numbers (one from each array) whose absolute difference is closest to zero,
and returns an array containing these two numbers, with the number from the first array in the first position.
Note that the absolut... |
class DiscountFactor:
def __init__(self, curve_date, day_counter):
self.curve_date = curve_date
self.day_counter = day_counter
def calculate_year_fraction(self, t):
""" Return the discount factor using continuous compounding
:param t:
:return: e ^ [-r_0 (t) * year_fracti... |
#
# @lc app=leetcode id=15 lang=python3
#
# [15] 3Sum
#
# O(n^2) time | O(n) space
class Solution:
def threeSum(self, array, k=0):
array.sort()
ans = []
for i in range(len(array) - 1):
left = i + 1
right = len(array) - 1
if i > 0 and array[i] == array[... |
# Copyright (c) 2015-2022 Adam Karpierz
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
__import__("pkg_about").about("jtypes.pyjava")
__copyright__ = f"Copyright (c) 2015-2022 {__author__}" # noqa
|
INVALID_VALUE = -1
## @brief Captures an intraday best quote,i.e. the bid/ask prices/sizes
class Quote( object ):
def __init__( self, bid_price, bid_size, ask_price, ask_size ):
self.bid_price = bid_price
self.bid_size = bid_size
self.ask_price = ask_price
self.ask_size = ask_size
... |
# confirm that a given IP address is valid.
# naive solution
def validate_ip(ip_address):
"""An IP address consists of 32 bits, shown as 4 terms
of numbers from 0-255 represented in decimal form """
terms = ip_address.split(".")
if len(terms) != 4:
return False
for octet in range(0,4):
i... |
##python program to print a pattern
n=int(input("No of rows\n"))
for i in range(0,n):
for j in range (0,i+1):
print("*", end="")
print()
|
# DomirScire
A1=[1,4,9]
A2=[9,9,9]
def plus_one(A):
A[-1] += 1
for i in reversed(range(1, len(A))):
if A[i] != 10:
break
A[i]=0
A[i-1] += 1
if A[0] == 10:
A[0]=1
A.append(0)
return A
if __name__ == "__main__":
print(plus_one(A1))
print(plus... |
# coding=utf-8
"""
Async IRC Interface Library
"""
__all__ = ("protocol", "server")
|
def main():
a = int(input("first number: "))
b = int(input("second number: "))
c = int(input("third number: "))
if a == b or b == c or c == a:
message = "\ngood bye"
else:
if a > b:
if a > c:
largest_number = a
else:
largest_nu... |
"""Module with custom errors."""
class InferralError(Exception):
"""Error sent when an inferral failed."""
pass
class DatasetError(Exception):
pass
class DuplicationError(Exception):
pass
class ValidationError(Exception):
pass
|
messageGlobal = 'oi do global'
message = 'global = a'
def greet():
if True:
# local variable
message = 'local = b'
print(message)
print(messageGlobal)
greet()
print(message)
# não tem block level scope
|
BLACK = 1
WHITE = -1
EMPTY = 0
symbols = {BLACK: 'X', WHITE: 'O', EMPTY: '.'}
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
##
# Copyright 2018 FIWARE Foundation, e.V.
# 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.apach... |
# -*- coding=utf-8 -*-
"""
自定义异常
"""
class MyError(Exception):
pass
class ArgumentsException(MyError):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return "argument error %s" % self.msg
|
def normalize_RTL(src: str):
"""
check if a string contains any non-english letters, and if so, return it appended by itself backwards
This is so it would be easy to read hebrew titles
"""
if not src.isascii():
return src + ' (' + src[::-1] + ')'
return src
_safe_chars = frozenset(" ._... |
OCTICON_DIFF = """
<svg class="octicon octicon-diff" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M8.75 1.75a.75.75 0 00-1.5 0V5H4a.75.75 0 000 1.5h3.25v3.25a.75.75 0 001.5 0V6.5H12A.75.75 0 0012 5H8.75V1.75zM4 13a.75.75 0 000 1.5h8a.75.75 0 100-1.5H4z"></p... |
#!/usr/bin/env python3
# create list
proto = ["ssh", "http", "https"]
# print entire list
print(proto)
# print second list item
print(proto[1])
# line add d, n, s
proto.extend("dns")
print(proto)
|
print("Welcome to Hangman")
name=input("What's your name?")
print("Hi "+name)
print("_ _ _ _ _")
firstletter=input("What's your first letter?")
if firstletter==("a"):
print("a _ _ _ _")
secondletter=input("What's your second letter?")
if firstletter==("a"):
if secondletter==("p"):
print(... |
#
# PySNMP MIB module DLINK-3100-IpRouter (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-IpRouter
# Produced by pysmi-0.3.4 at Mon Apr 29 18:33:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
class Solution:
def firstUniqChar(self, s: str) -> int:
# warm-up
# check the xor
count = [0]*26
a = ord('a')
for achar in s:
position = ord(achar) - a
count[position] += 1
for i in range(len(s)):
position = ord(s[i]) - a
... |
def get_amble(idx, lines):
return lines[idx-25:idx]
def get_pair(idx, lines):
amble = get_amble(idx, lines)
for i in amble:
for j in amble:
if i > lines[idx] or j > lines[idx]:
continue
if i == j:
continue
if i + j == lines[idx]:
... |
arr=[0]*101
input();N=[*map(int,input().split())]
ans=0
for i in N:
if arr[i]==0: arr[i]=1
else: ans+=1
print(ans) |
'''Pedro comprou um saco de ração, com peso em quilos. Ele possui dois gatos, para os quais fornece a quantidade de ração em gramas. A quantidade diária de ração fornecida para cada gato é sempre a mesma. Faça um programa que receba o peso do saco de ração e a quantidade de ração fornecida para cada gato, calcule e mos... |
'''
Leetcode problem No 719 Find K-th Smallest Pair Distance
Solution written by Xuqiang Fang on 19 June, 2018
'''
class Solution(object):
def smallestDistancePair(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
print(nums)
... |
def twos_difference(lst):
slst = sorted(lst)
pairs = []
for i in range(len(slst)):
for j in range(1, len(slst)):
if slst[j] - slst[i] == 2:
pairs.append((slst[i], slst[j]))
return pairs |
def fractionSum(a, b):
c = a[1] * b[1]
d = a[0] * b[1] + b[0] * a[1]
gcd = getGcd(c, d)
return [d/gcd, c/gcd]
def getGcd(a, b):
while b:
a, b = b, a % b
return a
|
def tflm_kernel_friends():
return []
def tflm_audio_frontend_friends():
return []
def xtensa_fusion_f1_cpu():
return "F1_190305_swupgrade"
def xtensa_hifi_3z_cpu():
return "HIFI_190304_swupgrade"
def xtensa_hifi_5_cpu():
return "AE_HiFi5_LE5_AO_FP_XC"
|
'''
Problem:
Given a string, find the first un-repeated character in it.
'''
def unrepeated(target):
lookup = {}
# Build a lookup table.
for item in target:
lookup.setdefault(item, 0)
lookup[item] += 1
# Find the first non-repeated character.
for item in target:
if lookup... |
EV_SYN = 0x00
EV_KEY = 0x01
EV_REL = 0x02
EV_ABS = 0x03
EV_MSC = 0x04
EV_SW = 0x05
EV_LED = 0x11
EV_SND = 0x12
EV_REP = 0x14
EV_FF = 0x15
EV_PWR = 0x16
EV_FF_STATUS = 0x17
SYN_REPORT = 0
SYN_CONFIG = 1
REL_X = 0x00
REL_Y = 0x01
REL_Z = 0x02
REL_RX = 0x03
REL_RY = 0x04
REL_RZ = 0x05
REL_HWHEEL = 0x06
REL_DIAL = 0x07
R... |
"""
1. Write a Python program to get a directory listing, sorted by creation date.
2. Write a Python program to get the details of math module.
3. Write a Python program to calculate midpoints of a line.
4. Write a Python program to hash a word.
5. Write a Python program to get the copyright information.... |
GREEN = 24
RED = 26
BLUE = 22
WHITELIST = {"eb94294a", "044c4fd2222a80"}
SPINTIME = 3
BLINKFRACTION = 3
#espeak
ACCESSDENIED = "Access denied."
SPEAKSPEED = 140
SPEAKPITCH = 50
|
# table definition
table = {
'table_name' : 'ar_allocations',
'module_id' : 'ar',
'short_descr' : 'Ar allocation detail lines',
'long_descr' : 'Ar allocation detail lines',
'sub_types' : None,
'sub_trans' : None,
'sequence' : None,
'tree_params' : None,
'ro... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
# @desc Checking to see if a number is equal to another number
def is_equal(x, y):
return x == y
def main():
print(is_equal(3, 5))
print(is_equal(5, 4))
print(is_equal(15, 15))
if __name__ == '__main__':
main()
|
# https://leetcode.com/problems/generate-parentheses/
# By Jiapeng
# Runtime: 24 ms, faster than 98.88% of Python3 online submissions for Generate Parentheses.
# Memory Usage: 14.2 MB, less than 29.90% of Python3 online submissions for Generate Parentheses.
# DFS框架参考2:此方法可以作为DFS参考框架
class Solution:
def generatePar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 9 17:54:03 2019
Exam 2 Physical Pendulum
@author: Lauren King
"""
"""
import numpy as np
import scipy as sc
#t=np.arange(0,10.001,.01)
#y=np.arange(0,10.001,.01)
#y[0]=.001
g=9.8
def f(m,ang):
f=m*g*np.sin(ang)
return f
m=2... |
s = "python3"
r = "raja"
sh = 'shobha'
iv = 'Ivaan'
ag = "34"
python_course = True
r_course = False
number_of_sisters = None
# print("Hi ", r.capitalize(), s.capitalize(), sh.upper())
# print(sh.isalpha())
# print(ag.isdigit())
# print("Hello, am {0}. Nice to meet you {1}.".format(r.capitalize(),sh.capitalize()))
p... |
# -*- coding: UTF-8 -*-
'''
Base Service Module
'''
class BaseService():
__repository = None
def __init__(self):
pass
|
# find the multiple missing numbers in an sorted array
# input Array elements
# find difference between currentArrayValue and value's index
# while i < arrayLength
# while difference < currentElementDifference (if missing elements are more than 1 at a time)
# then print the missing number (difference + currentIn... |
def format_log(info: str, exception=None, traceback: str=None, values: dict={}):
log = (
f'INFO: {info}\n'
f'------------\n'
)
if exception is not None:
log = log + (
f'EXCEPTION FOUNDED: \n'
f'{repr(exception)}\n'
f'------------\n'
)
if traceback is not None:
log = log + (
f'TRACEBACK: \n'
... |
nt_regex = {
'Matthew': '.*(M[a-z]*t[a-z]*)[\s\.](\d+):(\d+)[\s]*(.*)',
'Mark': '(M[a-z]*k[a-z]*)[\s\.](\d+):(\d+)[\s]*(.+)',
'Luke': '(L[a-z]*k[a-z]*)[\s\.](\d+):(\d+)[\s]*(.+)',
'John': '(^J[a-z]*n[a-z]*)[\s\.](\d+):(\d+)[\s]*(.+)',
'Acts': '(A[a-z]*c[a-z]*)[\s\.](\d+):(\d+)[\s]*(.+)',
'Romans... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def generateTrees(self, n: int):
def generateTrees(start, end):
if start > end:
... |
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 1
t = set(list(range(1, len(nums)+1))) - set(nums)
if len(t)==0:
return max(nums) + 1
w... |
"""Metrics-related functionality."""
# def df_classification_report(
|
#
# @lc app=leetcode id=206 lang=python3
#
# [206] Reverse Linked List
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
... |
def is_palindrome(word):
if word.lower() == word[::-1].lower():
print('Your word is a palindrome.')
else:
print('Your word is not a palindrome.')
def is_anagram(word1, word2):
w1 = sorted(word1.lower().replace(' ', ''))
w2 = sorted(word2.lower().replace(' ', ''))
if w1 == w2:
... |
"""
The ska_tmc_cdm.messages package contains modules that maps Tango structured
arguments to Python.
"""
|
def convert_newton_to(temperature_to: str, amount: float):
if temperature_to == 'celsiu(s)':
value = amount * (100 / 33)
if temperature_to == 'fahrenheit(s)':
value = amount * (60 / 11) + 32
if temperature_to == 'kelvin(s)':
value = amount * (100 / 33) + 273.15
if temperature_to ... |
#
# common.py
#
# Python utilities for bmk2.
#
# Copyright (c) 2015, 2016 The University of Texas at Austin
#
# Author: Sreepathi Pai <sreepai@ices.utexas.edu>
#
# Intended to be licensed under GPL3
# runs a python file and returns the globals
def load_py_module(f):
"""Executes a python file and returns the global... |
# Produce a list of list using list comprehensions
list1 = [1,2,3,4,5]
x = [[i**2, i**3] for i in list1]
print(x) |
# if a + b + c = P then we need a + b > c with c hypotenuse
# we can also say that a <= b
# Then we also need a^2 + b^2 = c^2
# We can start at 501 since all less than 501 will have a multiple
# less than 1000
def findTris(p):
''' Find potential triangle sides of perimeter p.
yield (a,b,c)
'''
maxC = ... |
class Solution:
def permute(self, nums):
if not nums or len(nums) == 0:
return []
def doPermute(numsLeft, numsChoosen, results):
if not numsLeft or len(numsLeft) == 0:
results.append(numsChoosen)
return
for i in range(len(n... |
class User:
def __init__(self, user_id: int, username: str):
self.user_id = user_id
self.username = username
self.books = []
def info(self):
return ', '.join(sorted(self.books))
def __str__(self):
return f"{self.user_id}, {self.username}, {self.books}"
|
"""
ШАШЕЧКИ
"""
class Checkers_figure(object):
def __init__(self, Table, pos_y, pos_x, color):
self.table = Table
self.y = pos_y
self.x = pos_x
self.color = color
self.symbol = ''
def move(self, pos_y, pos_x, pos_y_cut, pos_x_cut):
self.table.matrix[self.y][se... |
# Solution 1
# O(n^2) time / O(n^2) space
def sameBsts(arrayOne, arrayTwo):
if len(arrayOne) != len(arrayTwo):
return False
if len(arrayOne) == 0 and len(arrayTwo) == 0:
return True
if arrayOne[0] != arrayTwo[0]:
return False
leftOne = getSmaller(arrayOne)
leftTwo = getSm... |
class Bunch(dict):
def __init__(self, *args, **kwargs):
super(Bunch, self).__init__(*args, **kwargs)
self.__dict__ = self
|
class MetaData():
def save_data_source(self):
pass
|
ROBOT_LISTENER_API_VERSION = 2
def get_listener_method(name):
def listener_method(*args):
if name in ['message', 'log_message']:
msg = args[0]
message = '%s: %s %s' % (name, msg['level'], msg['message'])
else:
message = name
raise AssertionError(message)
... |
# 2-Sum Binary Tree
# https://www.interviewbit.com/problems/2sum-binary-tree/
#
# Given a binary search tree T, where each node contains a positive integer, and an integer K,
# you have to find whether or not there exist two different nodes A and B such that A.value + B.value = K.
#
# Return 1 to denote that two such n... |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we a... |
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
s=list(s)
left=0
right=len(s)-1
def isChar(a):
return (ord(a)>=ord('a') and ord(a)<=ord('z')) or (ord(a)>=ord('A') and ord(a)<=ord('Z'))
while left<right:
if isChar(s[left]) and isChar(s[righ... |
"""
Escreva um programa que leia 10 números inteiros e os armazene em um vetor. Imprima o vetor, o maior elemento e a
posição que ele se encontra.
"""
lista = []
for x in range(10):
n1 = int(input('Digite: '))
lista.append(n1)
for u in range(10):
if lista[u] == max(lista):
posicao = u
print(f'O ... |
# Shift cipher
def shift(plain, key):
if plain.isalnum() == False:
raise ValueError("Plaintext should be alphanumeric")
ctext = ""
for c in plain:
if c.islower():
ctext += chr((ord(c) - ord('a') + key) % 26 + ord('a'))
elif c.isupper():
ctext += chr(... |
p = []
i = 0
while i < 10:
p.append(i)
i += 1
p[2] = p[6] = p
p[a] = p # Makes p Top
|
n=str(input("Enter the list "))
ls=list(n.split(" "))
le=len(ls)
last=ls[le-1]
print("Last color %s"%last)
print("First color " +ls[0])
|
#Hay que crear una variable donde esta el objetivo, una lo que se va
# suman y otra donde esta lo que queda por cambiar
dinero=100
acumulado=0
resto=100
#Variable lista con billetes
billetes=[[3,20],[5,10],[2,5]]
#variable cambio
cambio2=[[0,20],[0,10],[0,5]]
cambio=cambio2.copy()
#soluciones posibles
solucion=((0,0,0... |
def factorial(number):
if number==0:
return 1
return number*factorial(number-1)
if __name__=='__main__':
number=int(input('Ingrese un número'))
result=factorial(number)
print (result) |
"""
This file contians weird view protocol defintions.
"""
# Configuration options
WV_REQ_TIMEOUT = 0.5
# Weird view protocol definitions.
WV_DISC = "8737808B"
WV_DISC_REPLY = "134E3A9D"
WV_LIST = "7DE0B79C"
WV_LIST_REPLY = "57186F8A"
WV_UPDATE ... |
a = "test1"
b = "test2"
c = "test3"
print(2**100) |
def fa_icon(name):
'''
http://fontawesome.dashgame.com/
'''
return 'fa fa-%s'%name |
class Customer:
def __init__(self,name):
self.name=name
def greet(self,arg=None):
if arg==None:
print("Hello!")
else:
print("Hello",arg,"!")
def purchase(self,*items):
count=len(items)
print(self.name, "you have purchased", count,"item(s):")
... |
"""
LeetCode 30 Day Challenge: Perform String Shifts
Link: https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3299/
Written by: Mostofa Adib Shakib
Language: Python
Cutting and slicing strings in Python
array[0] = The left most character in the array
array[-1] = The right most char... |
# Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com
#
# 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 applica... |
class Hashtable:
def __init__(self):
self.size = 11
self.slots = [None] * self.size
self.data = [None] *self.size
def put(self, key, data):
hash_value = self.hash_function(key)
if self.slots[hash_value] == None:
self.slots[hash_value] = key
... |
def setup():
size (300,300)
background (100)
smooth()
noLoop()
def draw ():
strokeWeight(15)
str(100)
line (100,200, 200,100)
line (200,200, 100,100)
|
v1 = int(input('Qual o número: '))
print('{} x {} = {}'.format(v1, 1, v1*1))
print('{} x {} = {}'.format(v1, 2, v1*2))
print('{} x {} = {}'.format(v1, 3, v1*3))
print('{} x {} = {}'.format(v1, 4, v1*4))
print('{} x {} = {}'.format(v1, 5, v1*5))
print('{} x {} = {}'.format(v1, 6, v1*6))
print('{} x {} = {}'.format(v1, ... |
name = 'pyopengl'
version = '3.1.0'
authors = [
'Mike C. Fletcher <mcfletch@vrplumber.com>'
]
description = \
'''
Standard OpenGL bindings for Python.
'''
build_requires = [
'setuptools'
]
requires = [
'python'
]
variants = [
['platform-linux', 'arch-x86_64', 'os-CentOS-7']
]
uuid = '... |
n, m = map(int, input().split())
l = [*map(int, input().split())]
for _ in range(m):
l.sort()
l[0], l[1] = l[0]+l[1], l[0]+l[1]
print(sum(l))
|
def dictMerge(a, b):
for key, value in b.items():
if isinstance(value, dict):
if key in a:
dictMerge(a[key], value)
else:
a[key] = dict(value)
else:
a[key] = value
|
class Calculator:
def __init__(self,num1):
self.num1 = num1
def __add__(self,num2):
return self.num1 + num2.num1
def __mul__(self,num2):
return self.num1 * num2.num1
def __len__(self,str):
return len(self.str)
def __str__(self):
return ... |
# Copyright 2020 Google Inc. 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 law or a... |
v = int(input('Qual a velocidade do carro no radar? '))
if v > 80:
print(f'Você está acima da velocidade e vai ser multado em R${(v - 80)*7:.2f}')
print('Dirija com segurança, tenha um bom dia!')
|
# Copyright 2020 Plezentek, Inc. 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 law or... |
input = """
% Reported by Axel Polleres to trigger a bug with -OR.
true.
%actiontime(T) :- T < #maxint, #int(T).
location(t) :- true.
location(B) :- block(B).
% blocksC2.dl without free variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Blocks world domain description in C
% Elementary Act... |
SCRABBLE_LETTER_VALUES = {
"a": 1,
"b": 3,
"c": 3,
"d": 2,
"e": 1,
"f": 4,
"g": 2,
"h": 4,
"i": 1,
"j": 8,
"k": 5,
"l": 1,
"m": 3,
"n": 1,
"o": 1,
"p": 3,
"q": 10,
"r": 1,
"s": 1,
"t": 1,
"u": 1,
"v": 4,
"w": 4,
"x": 8,
... |
"""
Created on Mon Jul 26 17:23:16 2021
@author: Andile Jaden Mbele
"""
"""
1. number of times around loop is n
2. number of operations inside loop is a constant
3. overall just O(n)
"""
def fact_iter(n):
prod = 1
for i in range(1, n + 1):
prod *= i
return prod
|
def trace(matrix):
try:
return sum(matrix[i][i] for i in range(max(len(matrix), len(matrix[0]))))
except:
return None |
"""Pushserver base configuration.
"""
class Config(object):
"""Base Configuration.
This should contain default values that will be used by all environments.
"""
DEBUG = False
TESTING = False
SERVER_NAME = None
SENTRY_DSN = None
BLUEPRINTS = (
('flask.ext.sse.sse', '/stream')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.