content stringlengths 7 1.05M |
|---|
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = [[0]*(len(text1)+1) for _ in range(len(text2)+1)]
for i in range(1, len(text2)+1):
for j in range(1, len(text1)+1):
if text2[i - 1] == text1[j - 1]:
dp[i][j] = 1 +... |
"""
Reversed from binary_search.
Given a item, if the item in the list, return its index.
If not in the list, return the index of the first item that is larger than the the given item
If all items in the list are less then the given item, return -1
"""
def binary_search_fuzzy(a... |
SCRIPT="""
#!/bin/bash
# Generate train/test script for scenario "{scenario}" using the faster-rcnn "alternating optimization" method
set -x
set -e
rm -f $CAFFE_ROOT/data/cache/*.pkl
rm -f {scenarios_dir}/{scenario}/output/*.pkl
DIR=`pwd`
function quit {{
cd $DIR
exit 0
}}
export PYTHONUNBUFFERED="True"
TRA... |
#test for primality
def IsPrime(x):
x = abs(int(x))
if x < 2:
return False
if x == 2:
return True
if not x & 1:
return False
for y in range(3, int(x**0.5)+1, 2):
if x % y == 0:
return False
return True
def QuadatricAnswer(a, b, n):
return n**2 + a... |
class NoRecordsFoundError(Exception):
pass
class J2XException(Exception):
pass
|
"""
Profile ../profile-datasets-py/div52_zen50deg/038.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div52_zen50deg/038.py"
self["Q"] = numpy.array([ 1.619327, 5.956785, 4.367512, 5.966544, 5.988635,
7.336613, 6.150054, 10.02425 , ... |
n = int(input())
tl = list(map(int, input().split()))
m = int(input())
sum_time = sum(tl)
for _ in range(m):
p, x = map(int, input().split())
print(sum_time - tl[p-1] + x)
|
class Solution:
def reverseWords(self, s: str) -> str:
list_s = s.split(' ')
for i in range(len(list_s)):
list_s[i] = list_s[i][::-1]
return ' '.join(list_s)
print(Solution().reverseWords("Let's take LeetCode contest"))
|
class XmlConverter:
def __init__(self, prefix, method, params):
self.text = ''
self.prefix = prefix
self.method = method
self.params = params
def create_tag(self, parent, elem):
if isinstance(elem, dict):
for key, value in elem.items():
self.t... |
# https://stepik.org/lesson/3363/step/4?unit=1135
# Sample Input:
# Петров;85;92;78
# Сидоров;100;88;94
# Иванов;58;72;85
# Sample Output:
# 85.0
# 94.0
# 71.666666667
# 81.0 84.0 85.666666667
def calculate_students_performance(data):
result = [str((int(grade1) + int(grade2) + int(grade3)) / 3) for name, grade1, g... |
print('-------------------------------------------------------------------------')
family=['me','sis','Papa','Mummy','Chacha']
print('Now, we will copy family list to a another list')
for i in range(len(family)):
cpy_family=family[1:4]
print(family)
print('--------------------------------------')
print(cpy_fa... |
num = 1
num1 = 10
num2 = 20
num3 = 40
num3 = 30
num4 = 50
|
#TODO: Complete os espaços em branco com uma possível solução para o problema.
X, Y = map(int, input().split())
while ( X != Y):
floor = min(X, Y)
top = max(X, Y)
if (X < Y):
print("Crescente")
elif (X > Y):
print("Decrescente")
X, Y = map(int, input().split())
|
# example_traceback.py
def loader(filename):
fin = open(filenam)
loader("data/result_ab.txt")
|
#%%
#https://leetcode.com/problems/divide-two-integers/
#%%
dividend = -2147483648
dividend = -10
divisor = -1
divisor = 3
def divideInt(dividend, divisor):
sign = -1 if dividend * divisor < 0 else 1
if dividend == 0:
return 0
dividend = abs(dividend)
divisor = abs(divisor)
if divisor == ... |
times = 'atlético-MG','flamengo','palmeiras','bragantino','fortaleza','corinthians','internacional','fluminense','cuiabá','america-MG','atletico-GO','são paulo','ceara SC','athletico-PR','santos','bahia','sport recife','juventude','gremio','chapecoense'
print('OS 5 PRIMEIROS COLOCADOS')
while True:
#print(times[:5]... |
"""
Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha
separados os valores pares e ímpares. No final mostre os valores pares e ímpares em ordem crescente.
"""
lista = [[], []]
n = 0
for indice in range(0, 7):
n = int(input(f'Digite o {indice + 1}º val... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Counter(object):
''' Stores all the samples for a given counter.
'''
def __init__(self, parent, category, name):
self.parent = parent
sel... |
'''<yasir_ahmad>
WAP to create a function which takes 3 arguments (say a,b,ch) where a is length ;b is breadth and ch is choice whether to compute area or perimeter.
Note:- By default is should find area.
'''
def Area_Perimeter(a,b,ch=1):
"""
a(int): Length of the rectangle
b(int): Breadth o... |
#Faça um programa que tenha uma função chamada area(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a
#área do terreno.
def area(larg, comp):
a = larg * comp
print(f'A área do terreno {larg}x{comp} é de {a}m2')
print(f'Controle de Terrenos')
l = float(input('Largura (m):... |
load("@com_github_reboot_dev_pyprotoc_plugin//:rules.bzl", "create_protoc_plugin_rule")
cc_eventuals_library = create_protoc_plugin_rule(
"@com_github_3rdparty_eventuals_grpc//protoc-gen-eventuals:protoc-gen-eventuals", extensions=(".eventuals.h", ".eventuals.cc")
)
|
class GUIComponent:
def get_surface(self):
return None
def get_position(self):
return None
def initialize(self):
pass |
__author__ = 'Chirag'
'''iter(<iterable>) = iterator converts
iterable object into in 'iterator' so that
we use can use the next(<iterator>)'''
string = "Hello"
for letter in string:
print(letter)
string_iter = iter(string)
print(next(string_iter))
|
def val_to_list(val):
"""
Convert a single value string or number to a list
:param val:
:return:
"""
if val is not None:
if not isinstance(val, (list, tuple)):
val = [val]
if isinstance(val, tuple):
val = list(val)
return val
def one_list_to_val(val)... |
class InfrastructureException(Exception):
"""
Custom exception to be raised to indicate a infrastructure function has failed its checks.
You should be explicit in such checks.
"""
pass
|
x = int (input('Digite um numero :'))
for x in range (0,x):
print (x)
if x % 4 == 0:
print ('[{}]'.format(x)) |
#try out file I/O
myfile=open("example.txt", "a+")
secondfile=open("python.txt", "r")
for _ in range(4):
print(secondfile.read())
|
"""
Non Leetcode Question:
https://www.educative.io/courses/grokking-the-coding-interview/YQQwQMWLx80
Given a string, find the length of the longest substring in it with no more than K distinct characters.
Example 1:
Input: String="araaci", K=2
Output: 4
Explanation: The lo... |
def nth_sevenish_number(n):
answer, bit_place = 0, 0
while n > 0:
if n & 1 == 1:
answer += 7 ** bit_place
n >>= 1
bit_place += 1
return answer
# n = 1
# print(nth_sevenish_number(n))
for n in range(1, 10):
print(nth_sevenish_number(n))
|
"""
creates decorator for class that counts instances
and allows to return and reset this value
"""
def instances_counter(cls):
"""Some code"""
setattr(cls, 'ins_cnt', 0)
def __init__(self):
cls.ins_cnt += 1
cls.__init__
def get_created_instances(self=None):
return cls.ins_cn... |
# coding=utf-8
"""
Manages a UDP socket and does two things:
1. Retrieve incoming messages from DCS and update :py:class:`esst.core.status.status`
2. Sends command to the DCS application via the socket
"""
|
# 분해합
# 브루트포스의 정석
# 각각 1부터 쭉 해주는 것에 for문을 쓰는데 인색하지 말자.
# 정말 앞에서부터 하나하나 쓰는 것을 중심으로 가야한다.
# [boj-백준] Brute force 2231 분해 합 - python
n = int(input())
for i in range(1, n+1):
a = list(map(int, str(i)))
sum_sep = sum(a)
sum_all = i + sum_sep
if sum_all == n:
print(i)
break
if i == n:
... |
'''
Find missing no. in array.
'''
def missingNo(arr):
n = len(arr)
sumOfArr = 0
for num in range(0,n):
sumOfArr = sumOfArr + arr[num]
sumOfNno = (n * (n+1)) // 2
missNumber = sumOfNno - sumOfArr
print(missNumber)
arr = [3,0,1]
missingNo(arr)
|
a = "python"
b = "is"
c = "excellent"
d = a[0] + c[0] + a[len(a)-1] + b
print(d)
|
# weekdays buttons
WEEKDAY_BUTTON = 'timetable_%(weekday)s_button'
TIMETABLE_BUTTON = 'timetable_%(attendance)s_%(week_parity)s_%(weekday)s_button'
# parameters buttons
NAME = 'name_button'
MAILING = 'mailing_parameters_button'
ATTENDANCE = 'attendance_button'
COURSES = 'courses_parameters_button'
PARAMETERS_RETURN = ... |
#coding:utf-8
MONGODB=('192.168.1.252',27017)
MONGODB=('127.0.0.1',27018)
# MONGODB=('192.168.1.252',27018)
STRATEGY_SERVER = MONGODB # 策略运行记录数据库
STRATEGY_DB_NAME = 'CTP_BlackLocust'
QUOTES_DB_SERVER = MONGODB # 行情历史k线数据库
TRADE_INTERFACE_SIMNOW = 'http://192.168.1.252:17001'
TRADE_INTER... |
class SearchParams(object):
def __init__(self):
self.maxTweets = 0
def set_username(self, username):
self.username = username
return self
def set_since(self, since):
self.since = since
return self
def set_until(self, until):
self.until = until
r... |
x = int(input("Please enter any number!"))
if x >= 0:
print( "Positive")
else:
print( "Negative") |
# IF
# In this program, we check if the number is positive or negative or zero and
# display an appropriate message
# Flow Control
x=7
if x>10:
print("x is big.")
elif x > 0:
print("x is small.")
else:
print("x is not positive.")
# Array
# Variabel array
genap = [14,24,56,80]
ganjil = ... |
num = int(input("1부터 9 사이 숫자를 입력하세요 : "))
for i in range(1, num+1):
if i % 2 != 0:
for j in range(1, num+1):
if j % 2 != 0:
print(j, end=' ')
else:
for j in range(1, num+1):
if j % 2 == 0:
print(' ', j, end='')
print('\n')
|
# Remember that everything in python is
# pass by reference
if __name__ == '__main__':
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print('First four: ', a[:4]) # same as a[0:4]
# -ve list index starts at position 1
print('Last four: ', a[-4:])
print('Middle two: ', a[3:-3])
# when used in... |
"""
@author: Alfons
@contact: alfons_xh@163.com
@file: 19-07-Property.py
@time: 18-8-18 下午7:22
@version: v1.0
"""
# ----------------------------------------原始------------------------------------------
class LineItem:
def __init__(self, description, weight, price):
self.description = description
se... |
## This script contains useful functions to generate a html page given a
## blog post txt file. It also creates meta data for the blog posts to be
## used to make summaries.
## Input should be a txt file of specific format
def read_file(infile):
metadata = []
post = []
with open(infile, 'r') as f:
... |
#!/usr/bin/env python
"""
check out chapter 2 of cam
"""
|
#!/usr/bin/env python3
#chmod +x hello.py
#It will insert space and newline in preset
print ("Hello", "World!")
|
"""Django Asana integration project"""
# :copyright: (c) 2017-2021 by Stephen Bywater.
# :license: MIT, see LICENSE for more details.
VERSION = (1, 4, 8)
__version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:])
__author__ = 'Steve Bywater'
__contact__ = 'steve@regionalhelpwanted.com'
__homepage__ = 'htt... |
def final_pos():
x = y = 0
with open("input.txt") as inp:
while True:
instr = inp.readline()
try:
cmd, val = instr.split()
except ValueError:
break
else:
if cmd == "forward":
x += int(val... |
class zoo:
def __init__(self,stock,cuidadores,animales):
pass
class cuidador:
def __init__(self,animales,vacaciones):
pass
class animal:
def __init__(self,dieta):
pass
class vacaciones:
def __init__(self):
pass
class comida:
def __init__(self,dieta):
pass
clas... |
PROLOGUE = '''module smcauth(clk, rst, g_input, e_input, o);
input clk;
input [255:0] e_input;
input [255:0] g_input;
output o;
input rst;
'''
EPILOGUE = 'endmodule\n'
OR_CIRCUIT = '''
OR {} (
.A({}),
.B({}),
.Z({})
);
'''
AND_CIRCUIT = '''
ANDN {} (
.A({}),
.B({}),
.Z({})
)... |
SINGLE_MATCHING_ITEM = """
<rss version="2.0">
<channel>
<item>
<title>testshow S02E03 720p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
SINGLE_ITEM_CAPITALISATION = """
<rss version="2.0">
<channel>
<item>
<title>TestShow S02E03 72... |
"""
Loop control version 1.1.10.20
Copyright (c) 2020 Shahibur Rahaman
Licensed under MIT
"""
# Pass
# Continue
# break
# A runner is practicing in a stadium and the coach is giving orders.
t = 180
for i in range(t, 1, -1):
t = t - 5
if t > 150:
print("Time:", t, "| Do another lap.")
continue
if t > 120:
... |
"""
Profile ../profile-datasets-py/div83/040.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/040.py"
self["Q"] = numpy.array([ 1.890026, 2.119776, 2.622053, 3.246729,
3.667537, 4.216342, 4.862296, 5.531749,
... |
class Base(object):
def __init__(self, *args, **kwargs):
pass
def dispose(self, *args, **kwargs):
pass
def prepare(self, *args, **kwargs):
pass
def prepare_page(self, *args, **kwargs):
pass
def cleanup(self, *args, **kwargs):
pass
|
"""Creates the train class"""
class Train:
"""
Each train in the metro is an instance of the Train class.
Methods:
__init__: creates a new train in the station
"""
def __init__(self):
self.cars = None
self.board_rate = 8
self.pop = None
self.travelers_exiting = ... |
n1 = float(input("Write the average of the first student "))
n2 = float(input("Write the average of the second student "))
m = (n1+n2)/2
print("The average of the two students is {}".format(m))
|
"""
https://www.codewars.com/kata/52742f58faf5485cae000b9a/train/python
Given an int that is a number of seconds, return a string.
If int is 0, return 'now'.
Otherwise,
return string in an ordered combination of years, days, hours, minutes, and seconds.
Examples:
format_duration(62) # returns "1 minute and 2 secon... |
"""
Takes BUY/SELL/HOLD decision on stocks based on some metrics
"""
def decision(ticker):
pass
|
"""
Module containing LinkedList class and Node class.
"""
class LinkedList():
"""
Class to generate and modify linked list.
"""
def __init__(self, arg=None):
self.head = None
if arg is not None:
if hasattr(arg, '__iter__') and not isinstance(arg, str):
for ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Elvis Tombini <elvis@mapom.me>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDE... |
# This programs aasks for your name and says hello
print('Hello world!')
print('What is your name?') #Ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The lenght of your name is : ')
print(len(myName))
print('What is your age?') #Ask for their age
yourAge = input()
print('You wil... |
# coding=utf8
"""all possible exceptions"""
class LilacException(Exception):
"""There was an ambiguous exception that occurred while
handling lilac process"""
pass
class SourceDirectoryNotFound(LilacException):
"""Source directory was not found"""
pass
class ParseException(LilacException):
... |
# project/tests/test_ping.py
def test_ping(test_app):
response = test_app.get("/ping")
assert response.status_code == 200
assert response.json() == {"environment": "dev", "ping": "pong!", "testing": True}
|
#!/usr/bin/env python
# coding=utf-8
__version__ = "2.1.4"
|
label_name = []
with open("label_name.txt",encoding='utf-8') as file:
for line in file.readlines():
line = line.strip()
name = (line.split('-')[-1])
if name.count('|') > 0:
name = name.split('|')[-1]
print(name)
label_name.append((name))
for item in label_name:... |
class Library(object):
def __init__(self):
self.dictionary = {
"Micah": ["Judgement on Samaria and Judah", "Reason for the judgement", "Judgement on wicked leaders",
"Messianic Kingdom", "Birth of the Messiah", "Indictment 1, 2", "Promise of salvation"]
}
def get(self, b... |
# Asal sayı: 1'den ve kendisinde başka sayıya bölünmeyen sayılar. 1'den büyük ve pozitif, minimum 2.
i = 155801
z = 0
with open("primenums.txt", "w") as fop:
while True:
i+=1
f = False
for x in range(2,i):
if i % x == 0:
f = True
if f == False:
... |
def split_full_name(string: str) -> list:
"""Takes a full name and splits it into first and last.
Parameters
----------
string : str
The full name to be parsed.
Returns
-------
list
The first and the last name.
"""
return string.split(" ")
# Test it out.
print(s... |
AESEncryptParam = "Key (32 Hex characters)"
S_BOX = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0... |
# -*- coding: utf-8 -*-
"""
Top-level package for Los Angeles
CDP instance backend.
"""
__author__ = "Matt Webster"
__version__ = "1.0.0"
def get_module_version() -> str:
return __version__
|
### Sherlock and The Beast - Solution
def findDecentNumber(n):
temp = n
while temp > 0:
if temp%3 == 0:
break
else:
temp -= 5
if temp < 0:
return -1
final_str = ""
rep_count = temp // 3
while rep_count:
final_str += "555"
rep_count... |
#!/bin/env python3
class Car:
''' A car description '''
NUMBER_OF_WHEELS = 4 # Class variable.
def __init__(self, name):
self.name = name
self.distance = 0
def drive(self, distance):
''' incrises distance '''
self.distance += distance
def reverse(distance):
... |
# LeetCode 953. Verifying an Alien Dictionary `E`
# 1sk | 97% | 22'
# A~0v21
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
dic = {c: i for i, c in enumerate(order)}
def cmp(s1, s2):
for i in range(min(len(s1), len(s2))):
if s1[i] != s2[i... |
def beautifulTriplets(d, arr):
t = 0
for i in range(len(arr)):
if arr[i] + d in arr and arr[i] + 2*d in arr:
t += 1
return t |
prime_numbers = [True for x in range(1001)]
prime_numbers[1] = False
for i in range(2, 1001):
for j in range(2*i, 1001, i):
prime_numbers[j] = False
input()
count = 0
for i in map(int, input().split()):
if prime_numbers[i] is True:
count += 1
print(count)
|
def intersection(right=[], left=[]):
return list(set(right).intersection(set(left)))
def union(right=[], left=[]):
return list(set(right).union(set(left)))
def union(right=[], left=[]):
return list(set(right).difference(set(left))) # not have in left
|
class Book:
"""The Book object contains all the information about a book"""
def __init__(self, title, author, date, genre):
"""Object constructor
:param title: title of the Book
:type title: str
:param author: author of the book
:type author: str
:param data: the date at which the book has been p... |
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... |
"""Workspace rules (Nixpkgs)"""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load(
"@io_tweag_rules_nixpkgs//nixpkgs:nixpkgs.bzl",
"nixpkgs_package",
)
def haskell_nixpkgs_package(
name,
attribute_path,
nix_file_deps = [],
repositories = {},
build_file_content = None,
... |
{
"target_defaults":
{
"cflags" : ["-Wall", "-Wextra", "-Wno-unused-parameter"],
"include_dirs": ["<!(node -e \"require('..')\")", "<!(node -e \"require('nan')\")",]
},
"targets": [
{
"target_name" : "primeNumbers",
"sources" : [ "cpp/primeNumbers.cpp" ],
"target_conditions": [
... |
"""Data for Python 3 style errors.
The following fields are rendered as HTML.
- solution
- explanation
"""
DATA = {
"E101": {
"original_message": "indentation contains mixed spaces and tabs",
"title_templated": False,
"title": "Line is indented using a mixture of spaces and tabs.",
... |
# 洗濯機
def get_E_Elc_washer_d_t(E_Elc_washer_wash_rtd, tm_washer_wash_d_t):
"""時刻別消費電力量を計算する
Parameters
----------
E_Elc_washer_wash_rtd : float
標準コースの洗濯の定格消費電力量,Wh
tm_washer_wash_d_t : ndarray(N-dimensional array)
1年間の全時間の洗濯回数を格納したND配列, 回
d日t時の洗濯回数が年開始時から8760個連続して格納されて... |
line = input()
a, b = line.split()
a = int(a)
b = int(b)
if a < b:
print(a, b)
else:
print(b, a)
"""nums = [int(i) for i in input().split()]
print(f"{min(nums)} {max(nums)}")"""
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def main():
print(add(5,10))
print(add(5))
print(add(5,6))
print(add(x=5, y=2))
# print(add(x=5, 2)) # Error we need to use the both with name if you use the first one as named argument
print(add(5,y=2))
print(1,2,3,4,5, sep=" - ")
def add(x, y=3):
total = ... |
"""Created by sgoswami on 7/3/17."""
"""Given two binary strings, return their sum (also a binary string).
For example,
a = \"11\"
b = \"1\"
Return \"100\"."""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bi... |
# 59. Spiral Matrix II
# O(n) time | O(n) space
class Solution:
def fillMatrix(self, spiralMatrix: [[int]], startIter: int, endIter: int, runningValue=1) -> None:
if startIter > endIter:
return
for index in range(startIter, endIter + 1):
spiralMatrix[startIter][inde... |
"""
Space = O(1)
Time = O(n log n)
"""
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
ans = 0
intervals.sort(key=lambda a: (a[0], -a[1]))
end = 0
for i, j in intervals:
if j > end:
ans += 1
end = max(end... |
AgentID = str
""" Assigned by Kentik """
TestID = str
""" Assigned by Kentik """
Threshold = float
""" latency and jitter in milliseconds, packet_loss in percent (0-100) """
MetricValue = float
""" latency and jitter in milliseconds, packet_loss in percent (0-100) """
|
#!/usr/bin/python3
class VectorFeeder:
def __init__(self, vectors, words, cursor=0):
self.data = vectors
self.cursor = cursor
self.words = words
print('len words', len(self.words), 'len data', len(self.data))
def get_next_batch(self, size):
batch = self.data[self.cursor:... |
expected_output = {
"instance": {
"default": {
"vrf": {
"VRF1": {
"address_family": {
"vpnv4 unicast RD 100:100": {
"default_vrf": "VRF1",
"prefixes": {
... |
n=6
x=1
for i in range(1,n+1):
for j in range(i,0,-1):
ch=chr(ord('Z')-j+1)
print(ch,end="")
x=x+1
print()
for i in range(n,0,-1):
for j in range(i,0,-1):
ch=chr(ord('Z')-j+1)
print(ch,end="")
x=x+1
print()
|
name1_1_0_0_0_0_0 = None
name1_1_0_0_0_0_1 = None
name1_1_0_0_0_0_2 = None
name1_1_0_0_0_0_3 = None
name1_1_0_0_0_0_4 = None |
def soma(*args):
total = 0
for n in args:
total += n
return total
print(__name__)
print(soma())
print(soma(1))
print(soma(1, 2))
print(soma(1, 2, 5)) |
infty = 999999
def whitespace(words, i, j):
return (L-(j-i)-sum([len(word) for word in words[i:j+1]]))
def cost(words,i,j):
total_char_length = sum([len(word) for word in words[i:j+1]])
if total_char_length > L-(j-i):
return infty
if j==len(words)-1:
return 0
return whitespace(w... |
class MinStack:
# Update Min every pop (Accepted), O(1) push, pop, top, min
def __init__(self):
self.stack = []
self.min = None
def push(self, val: int) -> None:
if self.stack:
self.min = min(self.min, val)
self.stack.append((val, self.min))
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 13:09:04 2020
@author: 766810
"""
tab = []
loop = 'loop'
# tab will hold all Kaprekar numbers found
# loop is just for better wording
def asc(n):
# puts the number's digits in ascending...
return int(''.join(sorted(str(n))))
def desc(n):
... |
def main():
try:
with open('cat_200_300.jpg', 'rb') as fs1:
data = fs1.read()
print(type(data))
with open('cat1.jpg', 'wb') as fs2:
fs2.write(data)
except FileNotFoundError as e:
print(e)
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
class Point:
def __init__(self, x, y, t, err):
"""
This class represents a gaze point
@param x:
@param y:
@param t:
@param err:
"""
self.error = err
self.timestamp = t
self.coord = []
self.coord.append(x)
self.coord.append(y)
def at(self, k... |
"""
*AbstractProperty*
"""
__all__ = ["AbstractProperty"]
class AbstractProperty:
pass
|
# -*- coding: utf-8 -*-
"""Conventions for data, coordinate and attribute names."""
measurement_type = 'measurement'
peak_coord = 'peak'
"""Index coordinate denoting passband peaks of the FPI."""
number_of_peaks = 'npeaks'
"""Number of passband peaks included in a given image."""
setpoint_coord = 'setpoint_index'
... |
while True:
a = input()
if a == '-1':
break
L = list(map(int, a.split()))[:-1]
cnt = 0
for i in L:
if i*2 in L:
cnt += 1
print(cnt)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.