content stringlengths 7 1.05M |
|---|
INTERACTIVE_TEXT_BUTTON_ACTION = "doTextButtonAction"
INTERACTIVE_IMAGE_BUTTON_ACTION = "doImageButtonAction"
INTERACTIVE_BUTTON_PARAMETER_KEY = "param_key"
def _respons_text_card(type,title,text):
return {
'actionResponse': {'type': type},
"cards": [
{
... |
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
l = 0
lis =[]
for i in nums:
if i != 0:
lis.append(i)
for i in lis:
... |
data = '''
Letters : abcdefghijklmnopqurtuvwxyz
Capital Letters : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Numbers : 1234567890
Words : regular expresion
Need to be escaped
Meta Characters : . ^ $ * + ? { } [ ] \ | ( )
Websites : qaviton.com yonadavking.com idangay.com
Phone Numbers:
... |
class PipelineNode(object):
def __init__(self, module_path, params):
self.module_path = module_path
self.params = params
|
script = """
from vapory import *
scene = Scene(
camera = Camera('location', [0, 2, -3], 'look_at', [0, 1, 2]),
objects = [
LightSource([2, 4, -3], 'color', [1, 1, 1]),
Background('color', [1, 1, 1]),
Sphere([0, 1, 2], 2, Texture(Pigment('color', ([1, 0, 1])))),
Box([{0}, -1.5, ... |
max = int(input())
bridges_height = input().split(" ")
# Перемен. для высчитвания высота моста относительно прошлого.
last_bridge_height = 0
for i in range(1, max + 1):
bridge_height = int(bridges_height[i - 1]) - last_bridge_height
if bridge_height <= 437:
print("Crash {}".format(i))
exit()
pr... |
if __name__ == "__main__":
filename = "ecm_flash_attempt2.in"
f = open(filename)
arr = []
i = 0
f2 = open(filename + ".dat", "w")
for line in f:
line = line.strip()
pieces = line.split(',')
can_data = pieces[3]
idh = can_data[0:5].replace(' '... |
def login():
result = auth_jwt.jwt_token_manager()
if result and "token" in result:
response.headers["x-gg-userid"] = auth.user_id
return result
def register():
request.vars.email = request.vars.username
request.vars.password = db.auth_user.password.validate(request.vars.password)[0]
re... |
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
max_alt = 0
curr = 0
for alt in gain:
curr += alt
if max_alt < curr:
max_alt = curr
return max_alt |
# Description: 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
#
# 字符 数值
# I 1
# V 5
# X 10
# L 50
# C 100
# D 500
# M 1000
#
# ... |
fields = 'Incorrect some fields'
login = 'Incorrect password or login'
location = 'Incorrect location'
wrong = 'Something goes wrong. Maybe some fields are incorrect. Please connect with administrations'
load = 'not loaded'
change = 'Somefing change on site. Please connect with administrations'
not_found = 'Article not... |
class Color:
def __init__(self, red, green, blue):
self.red = red
self.green = green
self.blue = blue
def get_color(self):
return self.red, self.green, self.blue
class BlockColor:
darkblue = Color(0, 0, 139)
yellow = Color(255, 255, 0)
green = Color(0, 128, 0)
... |
'''
Pattern:
Enter a number: 5
E
E D
E D C
E D C B
E D C B A
E D C B
E D C
E D
E
'''
print('Alphabet Pattern: ')
number_rows = int(input("Enter a number: "))
for row in range(1,number_rows+1):
for column in range(1,row+1):
print(chr(65+number_rows-column),end=" ")
print()
fo... |
# You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into ... |
# python3
def lps(pattern):
pattern = '#'+pattern
length = len(pattern)
table = [0 for i in range(length)]
table[1] = 0
for i in range(2, length):
j = table[i-1]
while pattern[j+1] != pattern[i] and j>0:
j = table[j]
if pattern[j+1... |
"""DLPack is a protocol for sharing arrays between deep learning frameworks."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo():
tf_http_archive(
name = "dlpack",
strip_prefix = "dlpack-3efc489b55385936531a06ff83425b719387ec63",
sha256 = "b59586ce69bcf3efdbf3cf4803fadfeaae4948... |
#!/usr/bin/env python
# coding: utf-8
# In[6]:
def Secant(f,a,b,nMax,epsilon):
fa=f(a)
fb=f(b)
if abs(fa) > abs(fb):
atemp = a
fatemp = fa
a = b
b = atemp
fa = fb
fb = fatemp
return None
print(0,a,fa)
print(1,b,fb)
for n in range(2,nMax)... |
#grade of steel
a=int(input("Hardness:"))
b=float(input("Carbon content:"))
c=int(input("Tensile strength:"))
if a>50 and b<0.7 and c>5600:
print("10")
elif a>50 and b<0.7:
print("9")
elif b<0.7 and c>5600:
print("8")
elif a>50 and c>5600:
print("7")
elif a>50 or b<0.7 or c>5600:
print(... |
# The basic parameters and file path should be explicit before trainning.
# The image that trainning directly in the deep learning model.
# The size of images should be small to prevent memory overflow.
img_h, img_w = 256, 256
# the classes number in this remote sensing semantic segmentation task
n_label = 6
# col... |
"""
练习1:将昨天作业day09/homework/exercise01功能改为函数
练习2:在终端中根据输入的选项,调用相应功能
"""
# ---------------全局变量-----------------------
list_commodity_infos = [
{"cid": 1001, "name": "屠龙刀", "price": 10000},
{"cid": 1002, "name": "倚天剑", "price": 10000},
{"cid": 1003, "name": "金箍棒", "price": 52100},
{"cid": 1004, "name": "口... |
'''1. Faça um programa que peça ao usuário um número e imprima todos os números de um até o número dado.
Exemplo: digite: 5, imprime: 1 2 3 4 5'''
print("{:^30}".format("LET'S GO"))
print('-'*30)
#Data input
num = int(input('Insert the number: '))
valor = 1
#Testing codicion for enter
while valor <= num:
print(v... |
def format_inequality_result_string(and_or_expr):
result = []
if and_or_expr.__class__.__name__ == 'Or':
if not and_or_expr.args:
raise ValueError('Recieved empty Or expression. Dafk?')
for expr in and_or_expr.args:
# TODO: This will fail when dealing with more complex bo... |
n = int(input())
M=[]
m = input().split()
for i in range(n -1):
for j in range(i+1,n):
if int(m[i])<int(m[j]):
M.append(m[j])
break
if len(M) < i+1:
M.append('*')
M.append('*')
m2 = ' '.join(M)
print(m2)
|
# Function to calculate the
# electricity bill
def calculateBill(units):
# Condition to find the charges
# bar in which the units consumed
# is fall
if (units <= 150):
return units * 5.50;
elif (151<=units<=300):
return ((150* 5.50... |
def compute_list_average(number_list):
return sum(number_list) / len(number_list)
number_list = []
for i in range(5):
number_list.append(float(input("Give a number: ")))
print(compute_list_average(number_list)) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:chuantong.py
@TIME:2020/4/17 21:57
@DES: 使用列表推导式
'''
#variable = [out_exp_res for out_exp in input_list if out_ex == 2]
# out_exp_res 列表生成元素表达式,可以有返回值的函数
squares = []
f... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 5 08:58:36 2020
@author: Shivadhar SIngh
"""
global_X = 27
def my_function(param1=123, param2="hi mom"):
local_X = 654.321
print("\n=== local namespace ===") # line 1
for name,val in list(locals().items()):
print("name:", name, "value:", val)
p... |
###############################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"). #
... |
a = int(input())
b = int(input())
c = int(input())
if a == b == c:
print(3)
elif (a == b and a != c) or (a == c and a != b) or (b == c and a != c):
print(2)
else:
print(0)
|
#triangular star pattern
'''
Print the following pattern for the given N number of rows.
Pattern for N = 4
*
**
***
****
'''
rows=int(input())
for i in range(rows):
for j in range(i+1):
print("*",end="")
print()
|
print("-- Cursos --")
print("Matemáticas - Biologia - Lenguas - Ciencias")
curso = input("Ingrese el curso deseado: ")
if curso in ("Matemáticas", "Biologia", "Lenguas", "Ciencias"):
print("Curso {0} seleccionado".format(curso))
else:
print("Este curso no existe...")
|
class ContestError(Exception):
def __init__(self, message: str = 'UGrade Error', *args) -> None:
super(ContestError, self).__init__(message, *args)
class NoSuchLanguageError(ContestError):
def __init__(self, message: str = 'No Such Language') -> None:
super(NoSuchLanguageError, self).__init__(... |
"""Using two methods from Stack, accomplish enqueue and dequeue."""
# from .. stack.stack import Stack
# from .. stack.stack import Node
class Node(object):
"""This class is set up to create new Nodes."""
def __init__(self, value, next_node=None):
self.value = value
self.next_node = next_node
... |
n = int(input())
if n % 2 == 1 or 6 <= n <= 20:
print('Weird')
elif 2 <= n <= 5 or n > 20:
print('Not Weird')
|
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
n = len(arr)
k = 1
m = 0
total_sum = 0
while k <= n:
for i in range(n - m):
total_sum = total_sum + sum(arr[i:i + k])
if k <= n:
k += 2
... |
# 選択ソート
n = int(input())
lst = list(map(int, input().split()))
def selectionSort(A, n):
cnt = 0
for i in range(n):
minj = i
for j in range(i, n):
if A[j] < A[minj]:
minj = j
if A[i] != A[minj]:
A[i], A[minj] = A[minj], A[i]
cnt += 1
... |
arquivo = open("exercicio_1.txt", "w")
arquivo.write("\nTeste 3")
arquivo.write("\nTeste 4")
arquivo.close()
arquivo = open("exercicio_1.txt", "a")
arquivo.write("\nTeste 5")
arquivo.write("\nTeste 6")
arquivo.close()
arquivo = open("exercicio_1.txt", "w")
arquivo.write("\nTeste 7")
arquivo.write("\nTeste 8")
arquivo... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp=head
dd=[]
## looping through the LInklist ... |
class Report:
def __init__(self):
self.set_age('')
self.set_date('')
self.set_cause('')
self.set_location('')
self.set_remarks('')
self.set_source('')
def clear():
self.data = []
def empty(self):
return (len(self.name) == 0)
... |
# -*- coding: utf-8 -*-
class Type(object):
""" Class who define a rule.
yml files are read from heimdall/conf/rules/type_name.yml and used for Type Object instantiation
Keyword Args:
:param: name: type's name.
:param: id: type's id.
:param: desc: type's d... |
class AbstractMiddleware:
def send_data(self):
pass
#def process_middleware_response(self):
# pass
|
# mock.py: module providing mock 10xGenomics data for testing
# Copyright (C) University of Manchester 2018 Peter Briggs
#
########################################################################
QC_SUMMARY_JSON = """{
"10x_software_version": "cellranger 2.2.0",
"PhiX_aligned": null,
"PhiX_error_... |
# Lab 3: String Data Type
# Exercise 1: The String Data Type
myString="This is a string."
print(myString)
print(type(myString))
print(myString + " is of data type " + str(type(myString)))
# Exercise 2: String Concatenation
firstString="water"
secondString="fall"
thirdString= firstString + secondString
... |
"""this module produces a SyntaxError at execution time"""
__revision__ = None
def run():
"""simple function"""
if True:
continue
else:
break
if __name__ == '__main__':
run()
|
def filter_child_dictionary(dictionary, key, value):
newdict = {}
for child_name in dictionary:
child = dictionary[child_name]
if not key in child:
continue
if str(child[key]) != str(value):
continue
newdict[child_name] = child
return newdict
def filter_child_attr(dictionary, key, ava... |
"""
Merged String Checker
http://www.codewars.com/kata/54c9fcad28ec4c6e680011aa/train/python
"""
def is_merge(s, part1, part2):
result = list(s)
def findall(part):
pointer = 0
for c in part:
found = False
for i in range(pointer, len(result)):
if result... |
# x = 0x0a
# y = 0x02
# z = x & y
# print(f'Hex: x = {x:02X}, y = {y:02X}, z = {z:02X}')
# print(f'Bin: x = {x:08b}, y = {y:08b}, z = {z:08b}')
x = 0x0a
y = 0x05
z = x ^ y
print(f'Hex: x = {x:02X}, y = {y:02X}, z = {z:02X}')
print(f'Bin: x = {x:08b}, y = {y:08b}, z = {z:08b}')
# x = 0x0a
# y = 0x02
# z ... |
"""Top-level package for Python Boilerplate."""
__author__ = """Evgeny Skosarev"""
__email__ = 'skosarew@mail.ru'
__version__ = '0.1.0'
|
# Dissecando uma variável:
# Exercício para testar tipos primitivos e informações sobre o que for digitado.
a = input('Digite algo: ')
print(type(a))
print('O valor digitado só tem espaços?', a.isspace())
print('O valor digitado é número?', a.isnumeric())
print('O valor digitado é alfanumérico?', a.isalnum())
print('O ... |
## Script (Python) "getFotos"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
root = context.portal_url.getPortalObject().getPhysicalPath()[1]
path = '/' + root + '/multimidia/fotos'
fotos = context.portal_catalog.searchRe... |
# Exercise 8.5
def rotate_char(c, n):
"""Rotate a single character n places in the alphabet
n is an integer
"""
# alpha_number and new_alpha_number will represent the
# place in the alphabet (as distinct from the ASCII code)
# So alpha_number('a')==0
# alpha_base is the ASCII code for the ... |
selfish_mining_strategy = \
[
[ # irrelevant
['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
['w', '*', 'a', '*', '*', '*', '*', '*', '*', '*'],
['w', 'w', '*', 'a', '*', '*', '*', '*', '*', '*'],
['w', 'w', 'w', '*', 'a', '*', '*', '*', '*', '*'],
['w', 'w', 'w', 'w', '... |
'''An example of an internal module within the package
Although the intenals are not explicity exposed, they are still available via
import mhlib
mhlib.eg.MhEg().runMhEg()
import mhlib.l2.l2
mhlib.l2.l2.L2EG_VAR
'''
|
# argparse
TRAIN_ARGS = [
'-i', 'flowers',
'-o', 'checkpoints',
'-a', 'resnet101',
'--input_size', '2048',
'--output_size', '102',
'--hidden_layers', '1024', '512',
'--learning_rate', '0.001',
'--epochs', '3',
'--gpu'
]
PREDICT_ARGS = [
'--input_img', 'flowers/test/1/image_06743... |
"""
the file was left blank
with much intent and purpose
Poetry needs it
"""
|
nome = input("digite seu nome aqui: ")
print("analizando seu nome...")
print("seu nome em maiúsculas é {}".format(nome.upper()))
print("seu nome em minúsculas é {}".format(nome.lower()))
print("seu nome tem ao todo {} letras".format(len(nome)- nome.count(" ")))
#print("seu primeiro nome é {} e ele tem {} letras".format... |
class CuentaBancaria():
def __init__(self, ID, titular, fecha_apertura, numero_cuenta, saldo):
self.ID = ID
self.titular = titular
self.fecha_apertura = fecha_apertura
self.numero_cuenta = numero_cuenta
self.saldo = saldo
#Método set
def setID(self, ID):
self... |
def ResponseModel(data,message):
return {
"data":[data],
"code":200,
"message":message
}
def ResponseCreateModel(message):
return {
"data": 1,
"code":201,
"message":message
}
def ErrorResponseModel(error,code,message):
return {
"error":error... |
__author__ = 'davidl'
class BaseMonitorDriver(object):
def notify(self,fixture_id, info):
print (info)
def notify_blocking_request(self,fixture_id, info):
print (info)
return True
|
new_list = []
people = ['agnes', 'andrew','jane','peter']
for person in people:
if person[0] == 'a':
new_list.append(person)
print(new_list) |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 14:04:13 2018
Created By: Ryan Boldi
"""
class Card(object):
"""Class of a Card object
"""
#ids go A -> K of Spades, A -> K of Diamonds,
#A -> K of Clubs, A -> K of Hearts
#Ace of spades is 0, king of hearts is 51`
colors = ["Red", "Black"]
... |
"""
This file contains a function used to assign the correct type
on a user entered equation.
"""
def type_check(some_input, memory):
"""
Assign the correct type on a user entered equation to avoid
accomodate a failure to input numbers in an equation.
:param some_input: an element from the user input... |
#Definir variables y otros
print("Ejercicio")
bono=0
#Datos de entrada
a=int(input("Años de trabajo:"))
#Proceso
if a==1:
bono=100
elif a==2:
bono=200
elif a==3:
bono=300
elif a==4:
bono=400
elif a==5:
bono=500
elif a>5:
bono=1000
#Datos de salida
print("El pago es de:", bono) |
# -*- coding: utf-8 -*-
#from gluon import *
#from s3 import *
# =============================================================================
class Daily():
""" Daily Maintenance Tasks """
def __call__(self):
# @ToDo: cleanup scheduler logs
return
# END ===================================... |
#------------------------------------------------------------------------------
# Copyright (c) 2007 by Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
""" Plug-ins for the Envisage application framework.
Part of the EnvisagePlugins project of t... |
try:
num1 = int(input("TELL ME YOUR AGE\n"))
num2 = int(input("TELL ME YOUR name\n"))
print(num1 + num2)
# print(num2)
except Exception as dfdfe:
print(dfdfe)
print("HELLO\n")
|
#类定义
class people:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造方法
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
#定义speak方法
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
#单继承类
cl... |
#
# PySNMP MIB module DFRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DFRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:42:12 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:23... |
#!/opt/evawiz/python/bin/python
#normal python defination code here
def pyAdd(x,y):
return abs(x)+abs(y)
|
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
best = 0
timeSpent = 0
h = []
current = 0
courses.sort(key=lambda x: x[1])
for duration, last in courses:
heapq.heappush(h, -duration)
timeSpent += duration
... |
# @Title: 适龄的朋友 (Friends Of Appropriate Ages)
# @Author: KivenC
# @Date: 2018-07-20 20:33:56
# @Runtime: 724 ms
# @Memory: N/A
class Solution(object):
def numFriendRequests(self, ages):
"""
:type ages: List[int]
:rtype: int
"""
# 年龄取值的范围比较小,1 <= ages[i] <= 120, 所以可以把所有的年龄都转... |
"""
Copyright (c) 2019 - Present – Thomson Licensing, SAS
All rights reserved.
This source code is licensed under the Clear BSD license found in the
LICENSE file in the root directory of this source tree.
"""
surpriseAlgo=["SVD","PMF","NMF","SVDpp","KNNWithMeans"]
f = open('commands.txt', 'w')
gitPath="~/b... |
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros
medida = float(input('Informe uma distância em metros: '))
km = medida / 1000
hm = medida / 100
dam = medida / 10
dm = medida * 10
ct = medida * 100
ml = medida * 1000
print('A medida de {:.1f}m corresponde a: \n{... |
"""
Approach 1: Brute Force
- O(n), O(1)
Approach 2: Binary Search
- O(log n), O(1)
Approach 3: Binary Search on Evens Indexes Only
- O(log n), O(1)
"""
class Solution:
def singleNonDuplicate1(self, nums: List[int]) -> int:
for i in range(0, len(nums) - 2, 2):
if nums[i] != nums[i + 1]:
... |
modlist = [
("Pmv","SLCommands","""None"""),
("Pmv","amberCommands","""None"""),
("Pmv","artCommands","""None"""),
("Pmv","bondsCommands","""None"""),
("Pmv","colorCommands","""
This Module implements commands to color the current selection different ways.
for example:
by atoms.
by residues.
by chains.
... |
# -*- coding:utf-8 -*-
WENCAI_LOGIN_URL = {
"scrape_transaction": 'http://www.iwencai.com/traceback/strategy/transaction',
"scrape_report": 'http://www.iwencai.com/traceback/strategy/submit',
'strategy': 'http://www.iwencai.com/traceback/strategy/submit',
"search": "http://www.iwencai.com/data-robot/e... |
class ConfigAttributeDataTypes:
data_types = {
0: 'None',
1: 'Base64',
2: 'Boolean',
3: 'CaseExactString',
4: 'CaseIgnoreList',
5: 'CaseIgnoreString, String',
6: 'Counter',
7: 'DistinguishedName',
8: 'EMailAddress',
9: 'FaxNum... |
# Python code to demonstrate the working of
# "+" and "*"
# initializing list 1
lis = [1, 2, 3]
# initializing list 2
lis1 = [4, 5, 6]
# using "+" to concatenate lists
lis2= lis + lis1
# priting concatenated lists
print ("list after concatenation is : ", end="")
for i in range(0,len(lis2)):
print (lis2[i... |
"""
12-1 lambda 表达式
"""
# 匿名函数/ lambda 表达式
# 定义函数的时候不需要定义函数名。
# 函数的基本定义:
def add(x,y):
return x+y
# 匿名函数
# lambda parameter_list: expression
# 学习匿名函数最好的方式:对比普通函数一起学习。
# lambda 后面的 expression 只能是一些简单的表达式,不能完整地实现函数内部的代码块。
lambda x, y: x+y # add 函数使用匿名函数实现
# 匿名函数与add函数的区别:
# 匿名函数没有 add 名字
# 不需要 return 语句返回。冒号... |
"""Kata: Get nth even number - Return the nth even number.
#1 Best Practices Solution by tedmiston, tachyonlabs, OQth, and others.
def nth_even(n):
return n * 2 - 2
"""
def nth_even(n):
"""Function I wrote that returns the nth even number."""
return (n * 2) - 2
|
# -*- coding: utf-8 -*-
stuff = ['hello', 'hi', 'how are you doing', 'im fine', 'how about you']
length_of_stuff = len(stuff)
index = 0
while index < length_of_stuff:
print(stuff[index])
index += 1
|
# Returns list of a specific attribute in yaml file. Attribute could be aliases/filter/category/id.
def icon_list(p_list, *pos):
if pos:
return [p_list[i][pos[0]] for i in range(len(p_list)) if (p_list[i][pos[0]] is not None)]
else:
return [p_list[i][2] for i in range(len(p_list))]
# Displays l... |
for x in range(10):
pass
for x in range(5):
a += x
b += 2
if False:
break
else:
continue
else:
c = 3
for index, val in enumerate(range(5)):
val *= 2
|
# Que 20 Leap Year
print ("Leap Year Has 366 Days...")
print ('The Year Perfectly Divisible by 4 is A Leap Year')
z=0
for i in range(2010,2101,1):
if i%4==0:
z=z+1
if z<=10:
print(i,end=" ")
else:
z=1
print()
print(i,end=" ")
|
def get_ns_declare(fd):
while True:
line = fd.readline()
if line.strip().startswith('(ns'):
return line
def get_ns(filename):
with open(filename, 'r') as infile:
ns_declare = get_ns_declare(infile)
splited = ns_declare.split()
ns = splited[-1]
if ns.... |
num1 = int(input())
num2 = int(input())
if num1 > num2:
print(num1-num2)
else:
print(num1+num2) |
"""
Tuples
"""
# A tuple is a collection which is ordered and unchangeable
# 1. In Python, tuples are written with round brackets
thistuple = ("apple", "banana", "cherry")
print(thistuple)
# 2. accessing
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
# 3. reverse indexing
thistuple = ("apple", "banan... |
print("The code point of symbol я = ",ord('я') )
# 1103
print("The symbol, represented by code point 1103 = ", chr(1103) )
# я
print("Symbols, represented by code points 9745 - 9750")
for i in range(9745, 9751):
print( chr(i), end=" " )
# U+0488
print("\u0488") |
def gp(a,r,n):
for i in range(n):
temp = a*pow(r,i)
print(temp,end=" ")
a = int(input())
r = int(input())
n = int(input())
gp(a,r,n)
|
class BatchReferenceSampler:
def __init__(
self, dataset, batch_size, label_sampler, annotation_sampler, point_sampler
):
self._dataset = dataset
self._batch_size = batch_size
self._label_sampler = label_sampler
self._annotation_sampler = annotation_sampler
self.... |
name = 'pybk8500'
version = '1.2.0'
description = 'BK-8500-Electronic-Load python library'
url = 'https://github.com/justengel/pybk8500'
author = 'Justin Engel'
author_email = 'jtengel08@gmail.com'
|
"""Base classes."""
class BaseEstimator:
"""Base class for all estimators."""
def __init__(self):
self._parameters = {}
self._residuals = None
self._fitted = False
self._t = None
self._y = None
self._y_predict = None
@property
def parameters(self):
... |
"""
https://www.ssa.gov/oact/babynames/decades/names2010s.html
"""
first_names_male = """
noah liam jacob william mason ethan michael alexander james elijah benjamin daniel aiden logan jayden
matthew lucas david jackson joseph anthony samuel joshua gabriel andrew john christopher olive dylan carter
isaac luke henry o... |
# 1.11
# Replace list elements
#Replacing list elements is pretty easy. Simply subset the list and assign new values to the subset. You can select single elements or you can change entire list slices at once.
#Use the IPython Shell to experiment with the commands below. Can you tell what's happening and why?
#x = ["a... |
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
ans = []
todo = []
todo_size = 0
def combine(todo, todo_size):
spaces = maxWidth - todo_size
if len(todo) == 1:
return todo[0] + " " * spaces
b... |
# Python - 3.6.0
BASIC_TESTS = (
(('45', '1'), '1451'),
(('13', '200'), '1320013'),
(('Soon', 'Me'), 'MeSoonMe'),
(('U', 'False'), 'UFalseU')
)
test.describe('Basic Tests')
for pair, result in BASIC_TESTS:
test.it("'{}', '{}'".format(*pair))
test.assert_equals(solution(*pair), result)
|
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
m = [[1]*i for i in range(1 , numRows + 1 )]
for i in range(numRows):
for j in range(1 , len(m[i]) - 1):
m[i... |
#list_intro.py
#What is a list?
# A collection of items in a particular order.
# Ex: The alphabet, digits 0-9, names of family
# Typically we will plural nouns for list names
star_treks = ['TOS', 'TNG', 'Voyager', 'DS9']
#print(star_treks)
#Accessing Elements
#Because lists are ordered, each element has an ind... |
# Preencha as informações pessoais nas variáveis abaixo
nome = "Nome Completo"
matricula = "12/3456789"
email = "foo@bar.com"
|
"""
Exercício Python 33:
Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
"""
print('-' * 30)
print(f'{"Valores - Maior e Menor":^30}')
print('-' * 30)
num1 = int(input('Digite o 1º número: '))
num2 = int(input('Digite o 2º número: '))
num3 = int(input('Digite o 3º número: '))
maior = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.