content stringlengths 7 1.05M |
|---|
while True:
flagGreen = hero.findFlag("green")
flagBlack = hero.findFlag("black")
if flagGreen:
pos = flagGreen.pos
hero.buildXY("fence", pos.x, pos.y)
hero.pickUpFlag(flagGreen)
if flagBlack:
pos = flagBlack.pos
hero.buildXY("fire-trap", pos.x, pos.y)
... |
# This function modifies global variable 's'
def f():
global s
print (s)
s = "Look for Wikitechy Python Section"
print (s)
# Global Scope
s = "Python is great!"
f()
print (s) |
data = input("File where data is stored: ")
content = open(data, 'r')
text = content.read()
option = input("Read or write: ")
if option == "read":
for i in content.readlines():
first_name, last_name, dob = i.split(",")
print(first_name, last_name, dob)
content.close()
elif option == "write":
... |
"""
{{cookiecutter.package_name}}.data
{% for _ in cookiecutter.package_name %}{{"~"}}{% endfor %}~~~~~
This module contains functionality for downloading, cleansing, and/or
generating data for this project.
**Module functions:**
.. autosummary::
placeholder
|
"""
def placeholder():
"Placeholder function ... |
class TwoHeadDragon():
def __init__(self):
self.left_head = IceDragon(self)
self.right_head = FireDragon(self)
def ice_breath(self):
return self.left_head.ice_breath()
def fire_breath(self):
return self.right_head.fire_breath()
def get_left_head(self):
return s... |
def MesPorExtenso(mes):
if mes == 1:
return "Janeiro"
elif mes == 2:
return "Fevereiro"
elif mes == 3:
return "Março"
elif mes == 4:
return "Abril"
elif mes == 5:
return "Maio"
elif mes == 6:
return "Junho"
elif mes == 7:
return "Julho"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
m = input("Введите предложение")
for i in range(len(m)):
if (i+1)%3 == 0:
print(m[i]) |
def grader(score: float) -> str:
"Translated scores into grade code letter."
TRANSLATE = ((0.9,"A"), (0.8,"B"), (0.7,"C"), (0.6,"D"))
if score > 1 or score < 0:
# Error case, score out of range
return 'F'
for limit,code in TRANSLATE:
if score >= limit:
return code
... |
#!/bin/python3
t = int(input().strip())
for _ in range(0, t):
n = int(input().strip())
flag = False
strings = [''.join(sorted(input().strip())) for line in range(0, n)]
for column in range(0, len(strings[0])):
for row in range(1, n):
up = strings[row-1][column]
now = s... |
N = int(input())
m2 = 0
m3 = 0
m4 = 0
m5 = 0
values = input().split(' ')
values_correctly = values[:N]
for i in range(N):
values_correctly[i] = int(values_correctly[i])
if(values_correctly[i] % 2 ==0):
m2+=1
if(values_correctly[i] % 3 ==0):
m3+=1
if(values_correctly[i] % 4 ==0):
... |
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
# two pass
# check adjacent elements
return all(A[i]<=A[i+1] for i in range(len(A)-1)) or all(A[i]>=A[i+1] for i in range(len(A)-1))
# Time: O(N)
# Space:O(1)
# One pass
class Solution(object):
def isMonotonic(se... |
# Data parsing constants
US_STATE_CODE_DICT = {'alabama': 0,
'alaska': 1,
'arizona': 2,
'arkansas': 3,
'california': 4,
'colorado': 5,
'connecticut': 6,
'delaware': 7,
... |
def convert_temp(unit_in, unit_out, temp):
"""Convert farenheit <-> celsius and return results.
- unit_in: either "f" or "c"
- unit_out: either "f" or "c"
- temp: temperature (in f or c, depending on unit_in)
Return results of conversion, if any.
If unit_in or unit_out are invalid, return "I... |
class TemplatesAdminHook(object):
'''
Hook baseclass
'''
@classmethod
def pre_save(cls, request, form, template_path):
pass
@classmethod
def post_save(cls, request, form, template_path):
pass
@classmethod
def contribute_to_form(cls, form, template_path):
r... |
#!/usr/bin/env python
class SNVMixRecord(object):
def __init__(self, line):
"""
:param line: a line of SNVMix2 output
:type line: str
"""
data = line.strip().split()
location = data[0].split(':')
self.chromosome = location[0]
self.position = int(loca... |
'''
2
Check if a number is odd or even
'''
def odd_or_even_using_modulus(n):
if n%2 == 0:
return("Even")
else:
return("Odd")
def odd_or_even_using_bitwise_and(n):
if n&1 == 0:
return("Even")
else:
return("Odd")
if __name__ == "__main__":
n = int(input("Number? ... |
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
def recursion(startIdx, endIdx):
if startIdx >= endIdx: return True
curIdx = startIdx
while postorder[curIdx] < postorder[endIdx]:
curIdx += 1
rightStartIdx = curIdx
while postorder[curIdx] > postorder[e... |
"""
from : https://leetcode.com/problems/candy-crush/discuss/1028524/Python-Straightforward-and-Clean-with-Explanation
Don't be intimidated by how long or ugly the code looks. Sometimes I fall into that trap. It's simpler than it seems.
Also, I would love feedback if this is helpful, or if there are any mistakes!
A ke... |
# darwin64.py
# Mac OS X platform specific configuration
def config(env,args):
debug = args.get('debug',0)
if int(debug):
env.Append(CXXFLAGS = env.Split('-g -O0'))
else:
env.Append(CXXFLAGS = '-O')
env.Append(CPPDEFINES= 'NDEBUG')
env.Append(CPPDEFINES= 'WITH_DEBUG')
env... |
# fazendo novamente
l = []
p = 0
for c in range(0, 5):
n = int(input(f'Digite o {c+1}º valor inteiro:'))
if len(l)==0:
l.append(n)
print(f'{n} adicionado na lista.')
elif n>l[-1]:
l.append(n)
print(f'Adicionado {n} no final da lista.')
else:
for k in range(0, 5):
... |
class ProjectView(object):
def __init__(self, project_id, name, status, selected_cluster_id):
self.id = project_id
self.name = name
self.status = status
self.selected_cluster_id = selected_cluster_id
class ClusterView(object):
def __init__(self, cluster_id, anchor, selected=... |
b2bi_strings = {
19: "g1VrCfVNFH+rV57qwbKeQla3oBPyyFjb4gEwtD6wgY2IlHxi8PIxjhilZLQd3c+N2dF9vKj79McEnR128FDVDU7ah4JipfLyAoRr8uy7R4FirnY8Xox1OSAS23Chz39lWmFFAq0lmg0C5s62acgk2ALzDECWwvguqPfmsc+Uv77MtWF1ubIFwQEGJhtOCKDKTim1gG6E+eYH0k1NmX5orDwhHmDzdJAt8AcmIJKPxlSSxdrfmp+4iNaFdUMDqOHw38QBUydx36LhOqhwgmsjRMjTjAnYP+ccxUxg2vtU... |
"""Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the... |
class StringUtils(object):
@staticmethod
def get_first_row_which_starts_with(text, starts_with):
rows = str(text).split("\n")
for row in rows:
str_row = str(row)
if str_row.startswith(starts_with):
return str_row
@staticmethod
def get_value_afte... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class PinValidationError(Exception):
pass
class PinChangingError(Exception):
pass
class AccountWithoutBalanceError(Exception):
pass
class Account:
def __init__(self, id: str, pin: str, balance: float):
self.__id = id
self.__pin = pin
... |
num=int(input('Digite um número de 0 até 9999:'))
unidade=num%10
dezena=num//10%10
centena=num//100%10
milhar=num//1000%10
print('Unidade {}'.format(unidade))
print('Dezena {}'.format(dezena))
print('Centena {}'.format(centena))
print('Milhar {}'.format(milhar))
|
model_lib = {
'fasterrcnn_mobilenet_v3_large_320_fpn': {
'model_path': 'fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth',
'tx2_delay': 0.18,
'cloud_delay': 0.024,
'precision': None,
'service_type': 'object_detection'
},
'fasterrcnn_mobilenet_v3_large_fpn': {
... |
#
# PySNMP MIB module RBN-BIND-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-BIND-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:44:05 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,... |
"""Although you have to be careful using recursion it is one of those concepts you want to at least understand. It's also commonly used in coding interviews :)
In this beginner Bite we let you rewrite a simple countdown for loop using recursion. See countdown_for below, it produces the following output:
least unders... |
text = "W. W. W. S. S. S. S. W. W. S. UNLOCK FRONT DOOR. S. WAIT. NO. LOOK AT WEATHER. WAIT. N. W. W. S. W. N. GET FOLDER AND MASK. MOVE BODY. LOOK IN WASTE BASKET. GET CARD AND OBJECT. S. E. N. E. E. E. E. N. W. DROP PEN AND NOTEBOOK. GET WET OVERCOAT. E. E. E. E. SHOW FOLDER TO ASTRONAUT. SHOW CARD TO ASTRONAUT. EXAM... |
"""文字列基礎
文字列を特定の区切り文字で分割する方法
splitとrsplitの結果が変わる場合
[説明ページ]
https://tech.nkhn37.net/python-split-splitlines-partition/#splitrsplit
"""
sample_text1 = 'Python Java C C++ C# Go'
sample_text2 = 'Python|Java|C|C++|C#|Go'
# ===== splitとrsplitの分割結果が変わる場合
# 空白文字で分割
print('--- 空白で分割')
print(sample_text1.split(maxsplit=3))
pri... |
API_TOKEN = "xxxxxxxxx"
DEFAULT_REPLY = "Sorry but I didn't understand you"
PLUGINS = [
'slackbot.plugins'
] |
'''
You've been using list comprehensions to build lists of values, sometimes using operations to create these values.
An interesting mechanism in list comprehensions is that you can also create lists with values that meet only a certain condition. One way of doing this is by using conditionals on iterator variables. ... |
print("\n")
name = input("What's your name? ")
age = input("How old are you? ")
city = input("Where do you live? ")
print("\n")
print("Hello,", name)
print("Your age is", age)
print("You live in", city)
print("\n") |
"""
logalyzer:
Parses your bloated HTTP access logs to extract the info you want
about hits from (hopefully) real people instead of just the endless
stream of hackers and bots that passes for web traffic
nowadays. Stores the info in a relational database where you can
access it using all the power of SQL.
"""
|
#cerner_2tothe5th_2021
# Get all substrings of a given string using slicing of string
# initialize the string
input_string = "floccinaucinihilipilification"
# print the input string
print("The input string is : " + str(input_string))
# Get all substrings of the string
result = [input_string[i: j] for ... |
## За даним натуральним числом N виведіть таке найменше ціле число k, що 2ᵏ≥N.
##
## Операцією зведення в ступінь користуватися не можна!
##
## Формат введення
##
## Вводиться натуральне число.
##
## Формат виведення
##
## Виведіть відповідь до задачі.
n = int(input())
i = 1
z = 0
while i < n:
i = i * 2
z = z +... |
#Sasikala Varatharajan G00376470
#Program to find all divisors between the given two numbers
#In this program we are going to find the numbers divisble by 6 but not by 12
#Get two inputs from the user - As per the instructions it should use 1000 as int_From and 10000 as int_to.
#But I have given an option to the user... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
_, maxSum = self.maxPa... |
# Author: weiwei
class BaseEvaluator:
def __init__(self, result_dir):
self.result_dir = result_dir
def evaluate(self, output, batch):
raise NotImplementedError()
def summarize(self):
raise NotImplementedError()
|
#
# PySNMP MIB module HP-ICF-RIP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-RIP
# Produced by pysmi-0.3.4 at Mon Apr 29 19:22:40 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:... |
{
'name': "MOBtexting SMS Gateway",
'version': '1.0',
'author': "MOBtexting",
'category': 'Tools',
'summary':'MOBtexting SMS Gateway',
'description':'You can use sms template to send SMS using MOBtexting Intergration.',
'website': "http://www.mobtexting.com",
'depends': ['base','web',],
... |
n = input("digite algo: ")
print(type(n))
print('é um numero: ', n.isnumeric())
print('é um caractere: ', n.isalpha())
print('é alfabeticonumerico: ', n.isalnum())
print('é um caractere com espaco: ', n.isspace())
print('Todos caracteres minusculos: ', n.islower())
print('Todos caracteres maiusculo: ',n.isupper())
prin... |
"""
fake_libc.py
For PyPy.
"""
def regex_parse(regex_str):
return True
# This makes things fall through to the first case statement...
def fnmatch(s, to_match):
return True
|
def quicksort (lst):
if lst == []:
return []
else:
smallsorted = quicksort([x for x in lst[1:] if x <= lst[0]])
bigsorted = quicksort([x for x in lst[1:] if x > lst[0]])
return smallsorted + [lst[0]] + bigsorted
|
class Board():
def __init__(self):
self.grid = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0... |
aos_global_config.set('no_with_lwip', 1)
src = Split('''
soc/uart.c
main/arg_options.c
main/main.c
main/hw.c
main/wifi_port.c
main/ota_port.c
main/nand.c
main/vfs_trap.c
''')
global_cflags = Split('''
-m32
-std=gnu99
-Wall
-Wno-missing-field-initializers
-Wno-strict... |
myl1 = [1,2,3,4,5]
myl2 = myl1.copy()
print(id(myl1))
print(id(myl2))
print("Initially")
print(" myl1 is: ", myl1)
print(" myl2 is: ", myl2)
print("--------------------")
myl1[2] = 13
print("Modifying myl1")
print(" myl1 is: ", myl1)
print(" myl2 is: ", myl2)
print("--------------------")
myl2[3] = 14
print("Modifying ... |
'''
UFPA - LASSE - Telecommunications, Automation and Electronics Research and Development Center - www.lasse.ufpa.br
CAVIAR - Communication Networks and Artificial Intelligence Immersed in Virtual or Augmented Reality
Ailton Oliveira, Felipe Bastos, João Borges, Emerson Oliveira, Daniel Takashi, Lucas Matni, Rebecca A... |
larg = float(input('Qual é a largura da parede? '))
alt = float(input('Qual é a altura da parede? '))
área = larg * alt
print('A parede tem dimensões de {}x{} e a sua área é de {}m'.format(larg, alt, área))
tinta = área / 2
print('Para você pintar a parede, você vai precisar de {}l de tinta'.format(tinta))
|
if __name__=="__main__":
t=int(input())
while(t>0):
(n, k) = map(int, input().split())
li=list(map(int, input().split()[:n]))
min = 99999999
for i in range(len(li)):
if li[i] < min:
min=li[i]
if k-min > 0:
print(k-min)
else:... |
people = [
[['Kay', 'McNulty'], 'mcnulty@eniac.org'],
[['Betty', 'Jennings'], 'jennings@eniac.org'],
[['Marlyn', 'Wescoff'], 'mwescoff@eniac.org']
]
for [[first, last], email] in people:
print('{} {} <{}>'.format(first, last, email))
|
#!/usr/bin/python2
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Kaleb Roscco Horvath
#
# 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
# ... |
# Helper function to get the turning performance with moving in upward right lane and
# turn left.
def UpLeftRightLane(line1, line2, flag, x, y):
laneWidth = abs(line2[0][0]-line2[0][1])
half = line2[0][0] + laneWidth/2 + 2
Rang1_1 = [[half-2, half],[ line2[1][0], line2[1][1] ]]
Rang1_2 = [[half, half... |
a,b,c = input().split(" ")
A = int(a)
B = int(b)
C = int(c)
MAIORAB = (A + B + abs(A-B))/2
MAIOR = (MAIORAB + C + abs(MAIORAB - C))/2
print("%d eh o maior" %MAIOR)
|
'''
Exercise 11 (0 points).
Implement a function to compute the Hessian of the log-likelihood. The signature of your function should be,
'''
def hess_log_likelihood(theta, y, X):
"""Returns the Hessian of the log-likelihood."""
z = X.dot(theta)
A = np.multiply(X, logistic(z))
B = np.multiply(X, logist... |
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
'''
Hivy
----
Hivy exposes a RESTful API to the Unide (unide.co) platform. Create, destroy
and configure collaborative development environments and services around it.
:copyright (c) 2014 Xavier Bruhier.
:license: Apache 2.0, see LICENSE for more details.
'''
__... |
MEMORY_SIZE = 64 * 1024
WORD_LENGTH = 255
_IN = "IN" # constant to specify input ports
_OUT = "OUT" # constant to specify output ports
|
inputFile = "day13/day13_1_input.txt"
# https://adventofcode.com/2021/day/13
def deleteAndAddKeys(paperDict, keysToPop, keysToAdd):
for key in keysToPop:
del paperDict[key]
for key in keysToAdd:
if key not in paperDict:
paperDict[key] = True
def foldYUp(paperDict, y):
keysT... |
SPECIMEN_MAPPING = {
"output_name": "specimen",
"select": [
"specimen_id",
"external_sample_id",
"colony_id",
"strain_accession_id",
"genetic_background",
"strain_name",
"zygosity",
"production_center",
"phenotyping_center",
"projec... |
class Node:
def __init__(self, data=None):
self.__data = data
self.__next = None
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def next(self):
return self.__next
@next.setter
de... |
# 이름의 첫 이니셜을 반환하는 함수를 생성하세요.
# 인자:
# name: 사람의 이름
# force_uppercase: 이니셜을 항상 대문자로 표시할 지 여부를 나타냅니다.
# 반환 값:
# 전달 된 이름의 첫 이니셜
def get_initial(name, force_uppercase):
if force_uppercase:
initial = name[0:1].upper()
else:
initial = name[0:1]
return initial
# 이름을 묻고 이니셜을 반환
first_name = i... |
def metade(n, formato=False):
if formato:
return moeda(n/2)
else:
return n/2
def dobro(n, formato=False):
if formato:
return moeda(n*2)
else:
return n*2
def aumentar(n, qtde, formato=False):
if formato:
return moeda(n / 100 * (100 + qtde))
else:
... |
# Copyright (C) 2018-2021 Seoul National University
#
# 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... |
def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=True,
feature_vec=True):
"""
Function accepts params and returns HOG features (optionally flattened) and an optional matrix for
visualization. Features will always be the first return (flatten... |
n = int ( input ('Digite um número: '))
if (n % 2) == 0:
print ('Esse número é par')
else:
print ('Esse número é impar')
|
# Copyright (c) 2021-2022, NVIDIA CORPORATION. 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 ... |
def Part1():
File = open("Input.txt").read().split("\n")
Order = [3,1]
CurrentLocation = [0,0]
Trees = 0
while (CurrentLocation[1] < len(File)-1):
CurrentLocation[1] += Order[1]
CurrentLocation[0] += Order[0]
if File[CurrentLocation[1]][CurrentLocation[0] % 31] == "#":
... |
lista=[[],[]]
for i in range(0,7):
numero=int(input('Digite um valor: '))
if numero%2==0:
lista[0].append(numero)
else:
lista[1].append(numero)
lista[0].sort()
lista[1].sort()
print(f'Os valores pares foram {lista[0]} e os impares foram {lista[1]}') |
class Build:
def __init__(self, **CONFIG):
self.CONFIG = CONFIG
try: self.builtup = CONFIG['STRING']
except KeyError: raise KeyError('Could not find configuration "STRING"')
def __call__(self):
return self.builtup
def reset(self):
self.builtup = self.CONFIG['STRING'... |
class Check(object):
'''Base class for defining linting checks.'''
ID = None
def run(self, name, meta, source):
return True
|
# pylint: skip-file
# flake8: noqa
# noqa: E302,E301
# pylint: disable=too-many-instance-attributes
class RouteConfig(object):
''' Handle route options '''
# pylint: disable=too-many-arguments
def __init__(self,
sname,
namespace,
kubeconfig,
... |
class Observer:
"""
Abstract class for implementation of observers used to monitor EvolutionEngine process.
"""
def trigger(self, event):
"""
This function is trigger by EvolutionEngine when particular event occurs.
:param event: Event
"""
raise NotImplementedErr... |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# Solution 1:
# Time Complexity: O(n)
# Space Complexity: O(n)
# nums_sorted = sorted(nums)
# res = []
# for num in nums:
# res.append(nums_sorted.index(num))
# retu... |
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) < 2:
return len(s)
cur = 1
left = -1
max_length = 1
while cur < len(s):
rindex = cur - 1
while rindex >= 0:
... |
# jupyter_notebook_config.py in $JUPYTER_CONFIG_DIR
c = get_config()
# c.NotebookApp.allow_root = True
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888 # NOTE don't forget to open
c.NotebookApp.open_browser = False
c.NotebookApp.allow_remote_access = True
c.NotebookApp.password_required = False
c.NotebookApp.password... |
def to_separate_args(content: str, sep='|'):
return list(map(lambda s: s.strip(), content.split(sep)))
def prepare_bot_module(name: str):
if not name.startswith('cogs.'):
name = 'cogs.' + name
return name
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: system_certificate
short_description: Resource module for System Certificate
description:
- Manage operations upda... |
# Copyright (c) 2020 safexl
# A config file to capture Excel constants for later use
# these are also available from `win32com.client.constants`
# though not in a format that plays nicely with autocomplete in IDEs
# Can be accessed like - `safexl.xl_constants.xlToLeft`
# Constants
xlAll = -4104
xlAutomatic =... |
'''
Your function should take in a signle parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
print(word)
if len(word) < 2:
re... |
def triangle(rows):
spaces = rows
for i in range(0, rows*2, 2):
for j in range(0, spaces):
print(end = " ")
spaces -= 1
for j in range(0, i + 1):
print("$", end = "")
print()
triangle(5) |
def λ_term_to_str(λ_term):
if λ_term['type'] == 'value':
if type(λ_term['value']) is tuple:
# treat as an operation, the operation `:`
λ_term = { 'type': 'op'
, 'op': ':'
, 'val1': λ_term['value'][0]
, 'val2': λ_term['val... |
# list examples
a=['spam','eggs',100,1234]
print(a[:2]+['bacon',2*2])
print(3*a[:3]+['Boo!'])
print(a[:])
a[2]=a[2]+23
print(a)
a[0:2]=[1,12]
print(a)
a[0:2]=[]
print(a)
a[1:1]=['bletch','xyzzy']
print(a)
a[:0]=a
print(a)
a[:]=[]
print(a)
a.extend('ab')
print(a)
a.extend([1,2,33])
print(a)
|
class Message_Template:
def __init__(
self,
chat_id,
text,
disable_web_page_preview=None,
reply_to_message_id=None,
reply_markup=None,
parse_mode=None,
disable_notification=None,
timeout=None
):
self.chat_id = chat_id
self.text = text
self.disable_web_page_preview = disable_web_page_pre... |
# -*- coding: utf-8 -*-
"""
__init__.py
~~~~~~~~~~~~~~
Test package definition.
:copyright: (c) 2016 by fengweimin.
:date: 16/6/11
"""
|
'''
Design Amazon / Flipkart (an online shopping platform)
Beyond the basic functionality (signup, login etc.), interviewers will be
looking for the following:
Discoverability:
How will the buyer discover a product?
How will the search surface results?
Cart & Checkout: Users expect the cart and checkou... |
def list_open_ports():
pass
|
def swap_case(s):
str1 = ""
for i in range(len(s)):
if s[i].isupper():
str1 = str1+s[i].lower()
elif s[i].islower():
str1 = str1+s[i].upper()
else:
str1 = str1+s[i]
return str1
if __name__ == '__main__':
s = input()
result = ... |
# SPDX-FileCopyrightText: 2020 2019-2020 SAP SE
#
# SPDX-License-Identifier: Apache-2.0
API_FIELD_CLIENT_ID = 'clientId'
API_FIELD_CLIENT_LIMIT = 'limit'
API_FIELD_CLIENT_NAME = 'clientName'
API_FIELD_DOCUMENT_TYPE = 'documentType'
API_FIELD_ENRICHMENT = 'enrichment'
API_FIELD_EXTRACTED_HEADER_FIELDS = 'headerFields'
... |
"""File with cops"""
class Cop:
cop_conf = dict()
DEFAULT_CONFIG = {
'enabled': True
}
def processable(self):
return self.cop_conf.get('enabled', True)
class ICop:
cop_conf = dict()
@classmethod
def name(self):
"""The Cop name"""
class ITokenCop(ICop):
de... |
def selection_sort(arr):
comparisons = 1
for i in range(len(arr)):
comparisons += 1
min_idx = i
comparisons += 1
for j in range(i + 1, len(arr)):
comparisons += 2
if arr[min_idx] > arr[j]:
min_idx = j
arr[i], arr[min_idx] = arr[min_... |
# fail-if: '-x' not in EXTRA_JIT_ARGS
def dec(f):
return f
@dec
def f():
pass
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Andre Augusto Giannotti Scota (https://sites.google.com/view/a2gs/)
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_de... |
class Scene:
def __init__(self):
"""
A scene has multiple SceneObject
"""
self.objects = []
class SceneObject:
def __init__(self, pos, color):
"""
Object that belongs to a scene
Args:
pos(ndarray): Position in 3D space
color(ndarr... |
def register_init(func):
pass
def register_config(func):
pass
def register_read(func):
pass
def register_write(func):
pass
def info(msg):
print(msg)
|
class Solution:
def solve(self, words):
minimum = sorted(words, key = len)[0]
LCP = ''
for i in range(len(minimum)):
matches = True
curChar = minimum[i]
for j in range(len(words)):
if words[j][i] != curChar:
matches ... |
# -*- coding: utf-8 -*-
operation = input()
total = 0
for i in range(144):
N = float(input())
line = (i // 12) + 1
if (i < (line * 12 - line)):
total += N
answer = total if (operation == 'S') else (total / 66)
print("%.1f" % answer) |
# -*- coding: utf-8 -*-
'''
File name: code\onechild_numbers\sol_413.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #413 :: One-child Numbers
#
# For more information see:
# https://projecteuler.net/problem=413
# Problem Statement
'''
... |
#Desafio 12
#Programa Calculador de desconto
#Lê um valor e um desconto e calcula o preço final com desconto
valor = float(input("Digite aqui o valor do produto: "))
desconto = float(input("Digite aqui o valor do desconto, em porcentagem: "))
preco = valor * (100 - desconto)/100
print(f"Então, o produto que custa {valo... |
# A DP program to solve edit distance problem
def editDistDP(x, y):
m = len(x);
n = len(y);
# Create an e-table to store results of subproblems
e = [[0 for j in range(n + 1)] for i in range(m + 1)]
# Fill in e[][] in bottom up manner
for i in range(m + 1):
for j in range(n + 1)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.