content stringlengths 7 1.05M |
|---|
mystr = "Anupam"
newstr = ""
# Iterating the loop in backward direction.
# for char in mystr[::-1]:
for char in reversed(mystr):
newstr = newstr + char
print(newstr)
|
#
# PySNMP MIB module F3-TIMEZONE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/F3-TIMEZONE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:11:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
class EmptyContextManager:
"""
A context manager that does nothing. Only to support conditional change of context managers,
eg in such a way:
>>> if tx_enabled:
>>> ctxt = transaction.atomic
>>> else:
>>> ctxt = EmptyContextManager()
>>> with ctxt:
>>> ...
"""
de... |
def setup ():
size (500, 500)
smooth ()
background(255)
strokeWeight(30)
noLoop ()
def draw ():
stroke(20)
line(50*1,200,150+50*0,300)
line(50*2,200,150+50*1,300)
line(50*3,200,150+50*2,300)
|
def number_indice_to_string(index)->str:
"""
Convert a number to a string.
"""
indicename = ["x", "y", "z"]
return "".join([indicename[i] for i in index]) |
def validate_pin(pin):
if (len(pin) == 4 or len(pin) == 6) and pin.isdigit():
return True
else:
return False |
'''
- Leetcode problem: 351
- Difficulty: Medium
- Brief problem description:
Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock
patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.
Rules for a valid pattern:
... |
"""solved with help, hard """
class Solution:
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = []
while n > 0:
n -= 1
result.append(chr(n % 26 + 65))
n = n // 26
return ''.join(result[::-1])
if __nam... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Breno Alef Dourado Sá'
#Number of problem constraints
clausesCount = 0
#At least one queen on each line
#(p1 ∨ ... ∨ p4) ∧ ... ∧ (p13 ∨ ... ∨ p16)
def existence(n):
global clausesCount
clauses = ""
for i in range(0, n):
value = ""
for j in range(1,n+... |
"""Membership operators
@see: https://www.w3schools.com/python/python_operators.asp
Membership operators are used to test if a sequence is presented in an object.
"""
def test_membership_operators():
"""Membership operators"""
# Let's use the following fruit list to illustrate membership concept.
fruit... |
def moveElementToEnd(array, toMove):
# Write your code here.
left = 0
right = len(array) - 1
while left < right:
if array[right] == toMove:
right -= 1
elif array[left] != toMove:
left += 1
elif array[left] == toMove:
array[left], array[right] ... |
people = [
{"name": "Harry", "house":"Gryffibdor"},
{"name": "Ron", "house":"Ravenclaw"},
{"name": "Hermione", "house":"Gryffibdor"}
]
# def f(person):
# return person["house"]
people.sort(key=lambda person: person["house"])
print(people) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
PIXEL_ON = '#'
PIXEL_OFF = '.'
GROWTH_PER_ITERATION = 3
ITERATIONS_PART_ONE = 2
ITERATIONS_PART_TWO = 50
def filter_to_integer(image, x, y, default_value):
# The image enhancement algorithm describes how to enhance an image by simultaneously
# converting all pixels i... |
# FIBONACCI PROBLEM
# Write a function 'fib(N)' that takes in a number as an argument.
# The function should return the nth number of the Fibonnaci sequence.
#
# The 0th number of sequence is 0.
# The 1st number of sequence is 1.
#
# To generate the next number of the sequence,we sum the previous two.
#
# N ... |
#lg1009
def exp(n):
ans = 1
for i in range(2, n + 1):
ans *= i
pass
return ans
pass
n = int(input())
tot = 0
for i in range(1, n + 1):
tot += exp(i)
pass
print(tot)
|
'''
Problem Description:
------------------
The program takes a file name from the user and
reads the contents of the file in reverse order.
'''
print(__doc__,end="")
print('-'*25)
fileName=input('Enter file name: ')
print('-'*40)
print('Contents of text in reversed order are: ')
for line in reversed(list(o... |
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1 or not list2:
return list1 if list1 else list2
if list1.val > list2.val:
list1, list2 = list2, list1
list1.next = self.mergeTwoLists(lis... |
#exercicio 97
def escreva(txt):
c = len(txt)
print ('-'*c)
print (txt)
print ('-'*c)
escreva (' Exercicio97 ')
escreva (' resolvido ') |
# 74. Search a 2D Matrix
class Solution:
def searchMatrix(self, matrix: [[int]], target: int) -> bool:
"""
Efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The ... |
class Elemento:
dado = None
anterior = None
proximo = None
def __init__(self, dado, anterior=None, proximo=None):
self.dado = dado
self.anterior = anterior
self.proximo = proximo
class Lista:
cabeca = None
cauda = None
def __init__(self, elemento):
self.ca... |
"""Storage module for static ids of DataProviders for consistent access.
IDs stored in this module should not be modified programmatically for any reason. Don't do it.
"""
INDICATOR_BLOCK_PROVIDER_ID = "IndicatorBlockProvider"
CLUSTERED_BLOCK_PROVIDER_ID = "ClusteredBlockProvider"
SPLIT_BLOCK_PROVIDER_ID = "Sp... |
hexN = '0x41ba0320'
print(hexN)
hexP = hexN[2:]
print (hexP[0:2])
print (hexP[2:4])
print (hexP[4:6])
print (hexP[6:8])
print(hexP)
print("{}.{}.{}.{}".format(hexP[0:2],hexP[2:4],hexP[4:6],hexP[6:8])) |
# print('Hello, what is your name?') will type out the text in the ()
print('Hello, what is your name?')
# name = input() means that the name you typed is the answer to the question.
name = input()
# print('your name is '+name) will print the sentence plus the name you put in at name = input().
print('Your name is... |
#!/usr/bin/python3
# file: coroutine_3_生成器_1_fibonacci.py
# Created by Guang at 19-7-21
# description:
# *-* coding:utf8 *-*
def create_num(all_num):
a, b = 0, 1
current_num = 0
while current_num < all_num:
ret = yield a
print(">>>ret>>>>", ret)
a, b = b, a+b
current_num +... |
n,k = map(int,input().split())
l = list(map(int,input().split()))
l.append("fake")
idx=0
ans=[l[0]]
s=set(l)
for i in range(1,n*k+1):
if i not in s:
ans.append(i)
if len(ans)==n:
print(*ans)
idx+=1
ans=[l[idx]] |
class Solution:
def maxValue(self, grid: List[List[int]]) -> int:
if not grid:
return 0
m, n = len(grid), len(grid[0])
dp = [0] * n
for idx, _ in enumerate(grid[0]):
if idx == 0:
dp[idx] = _
else:
dp[idx] = _ + dp[id... |
NON_EMPTY_FILEKEYS = """
.Contents[]
| select(.Size > 0)
| .Key
| select(endswith(".jsonl"))
"""
EMPTY_FILEKEYS = """
.Contents[]
| select(.Size == 0)
| .Key
| select(endswith(".jsonl"))
"""
DELETE_FILTER = """
.ResponseMetadata | {HTTPStatusCode, RetryAtte... |
def yes_no_query():
result = input("[y/n | yes/no]")
result = result.lower()
if result == 'y' or result == 'yes':
return True
elif result == 'n' or result == 'no':
return False
else:
print("[Please Enter yes or no]")
return yes_no_query()
def do_discussion():
# ... |
load(
"//rules/common:private/utils.bzl",
_action_singlejar = "action_singlejar",
)
#
# PHASE: binary_deployjar
#
# Writes the optional deploy jar that includes all of the dependencies
#
def phase_binary_deployjar(ctx, g):
main_class = None
if getattr(ctx.attr, "main_class", ""):
main_class = ... |
"""
Discounts are determined by a combination of user and course, and have a one to one relationship with the enrollment
(if already enrolled) or a join table of user and course. They are determined in LMS, because all of the data for
the business rules exists here. Discount rules are meant to be permanent.
"""
|
def find_pattern(given):
total = len(given)
pattern = given[0]
to_compare = len(pattern)
for i in range(1, total):
for j in range(to_compare):
if given[i][j] != pattern[j]:
pattern = pattern[:j] + '?' + pattern[j + 1:]
return pattern
if __name__ == '__main__':
... |
"""Some utils to make parsing easier."""
def _string_to_db(stream: str) -> list:
db_values = []
if stream == '':
return db_values
escaped_actual = (
(r'\n', ord('\n')),
(r'\t', ord('\t'))
)
for c, val in escaped_actual:
if c in stream:
a, b = stream.spl... |
class DMIntervention(object):
"""DM人工干预"""
pass
|
x = float(input())
n = int(input())
def expo(x, n):
num = 1
den = 1
sumi = 1
if n == 1:
return 1
for cnt in range(1, n):
num *= x
den *= cnt
sumi += num / den
return sumi
print("{:.3f}".format(expo(x, n) ))
|
# fo =open("/disk/lulu/TCGA11.txt","w")
with open(r"/disk/lulu/TCGA1.txt","r") as TCGA:
temp=[]
cancerlist=[]
cancer =[]
for line in TCGA:
list = line.strip().split("\t")
temp = list[0]
cancerlist.append(temp)
cancer = sorted(set(cancerlist))
print (cancer)
... |
# https://www.hackerrank.com/challenges/strange-code/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign
starting = 3
index = 1
# time and value seperated by 2 min
time,value = [],[]
for i in range(1,40+1):
time.append(index) # time
value.append(starting) # value
inde... |
#
# PySNMP MIB module HPN-ICF-EPON-DEVICE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-EPON-DEVICE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:38:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
# Question Link : https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/552/week-4-august-22nd-august-28th/3436/
# Level : Hard
# Solution right below :-
class Solution(object):
def mincostTickets(self, days, costs):
"""
:type days: List[int]
:type costs: List[int]
... |
# comprehensive solution
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
# https://leetcode.com/problems/jewels-and-stones/discuss/527360/Several-Python-solution.-w-Explanation
jewel = set(J)
return sum( 1 for item in S if item in jewel )
def numJewelsInStones(s... |
TIEMPO_POR_INSTRUCCION = 15
TIEMPO_AVISO_NO_MOVIMIENTO = 10
constante_cambio_area = 1000 # constante de cambio de area, entre mayor sea el numero, mayor es el area a detectar para cambio, es decir el equivalente a la velocidad de movimiento
valor_cambio = 200 # Constante incremental para cambio de estado [Lavandose_... |
# -*- coding=utf-8 -*-
# library: jionlp
# author: dongrixinyu
# license: Apache License 2.0
# Email: dongrixinyu.89@163.com
# github: https://github.com/dongrixinyu/JioNLP
# description: Preprocessing tool for Chinese NLP
def bracket(regular_expression):
return ''.join([r'(', regular_expression, r')'])
def bra... |
"""
Programa VamoAI:
Aluna: Gisele Rodrigues Manuel
Atividade : Estrutura de repetição
Descrição do Exercício
Criar um programa com for com if;
"""
# cabeçalho do programa
print('-' * 25)
print(f'{"Contando até 10":^25}')
print('-' * 25)
# exibindo a contagem de 1 até 10
for conta_num in range (1,11):
if conta_n... |
t = int(input())
s = "abcdefghijklmnopqrstuvwxyz"
for _ in range(t):
total = 0
l = list(map(int, input().split()))
string = input()
lst = list(set(s) - set(string))
for i in lst:
total += l[ord(i) - ord('a')]
print(total) |
#
# License: BSD
# https://raw.githubusercontent.com/stonier/groot_tools/devel/LICENSE
#
##############################################################################
# Documentation
##############################################################################
"""
Groot tools and utilities
"""
##################... |
# Fury Incarnate
medal = 1142554
if sm.canHold(medal):
sm.chatScript("You obtained the <Fury Incarnate> medal.")
sm.startQuest(parentID)
sm.completeQuest(parentID) |
#
# PySNMP MIB module WHISP-SM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WHISP-SM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:36:30 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,... |
'''
The sum of the squares of the first ten natural numbers is,
1^2+2^2+...+10^2 = 385
The square of the sum of the first ten natural numbers is,
(1+2+...+10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025−385=2640.
Find the diff... |
"""Class to store customized UI parameters."""
class UIConfig():
"""Stores customized UI parameters."""
def __init__(self, description='Description',
button_text='Submit',
placeholder='Default placeholder',
show_example_form=False):
self.description ... |
#
# PySNMP MIB module NETSCREEN-SERVICE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSCREEN-SERVICE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:20:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
#
# PySNMP MIB module DT1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DT1-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:39:59 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:15)... |
# Copyright (c) 2006-2010 Tampere University of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modi... |
print(''' _____
.-" .-. "-.
_/ '=(0.0)=' \_
/` .='|m|'=. `\
\________________ /
.--.__///`'-,__~\\\\~`
/ /6|__\// a (__)-\\\\
\ \/--`(( ._\ ,)))
/ \\ ))\ -==- (O)(
/ )\((((\ . /)))))
/ _.' / __(`~~~~`)__
//"\... |
'''
Created on Dec 20, 2016
@author: bardya
'''
# HOG_herit = [0,1,2]
#
# hogset = set()
#
# for i in HOG_herit:
# fh = open("/share/project/bardya/Enterobacteriaceae/OMA_prot/HOGLevel_Gains/{}".format(i), 'r')
# hogset |= set([line.strip() for line in fh if line.strip()])
# fh.close()
#
# fh2 = ... |
class FModifierEnvelopeControlPoint:
frame = None
max = None
min = None
|
self.description = "Try to upgrade two packages which would break deps"
lp1 = pmpkg("pkg1")
lp1.depends = ["pkg2=1.0"]
self.addpkg2db("local", lp1)
lp2 = pmpkg("pkg2", "1.0-1")
self.addpkg2db("local", lp2)
p1 = pmpkg("pkg1", "1.1-1")
p1.depends = ["pkg2=1.0-1"]
self.addpkg(p1)
p2 = pmpkg("pkg2", "1.1-1")
self.addpk... |
def intersection_of(lhs, rhs):
"""
Intersects two posting lists.
"""
i = 0
j = 0
intersection = []
while (i < len(lhs) and j < len(rhs)):
if (lhs[i] == rhs[j]):
intersection.append(lhs[i])
i += 1
j += 1
elif (lhs[i] < rhs[j]):
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = Node(data)
if head == None:
head = p
elif head.next == None:
head.next = p
else:
start = head
... |
class Solution:
def isStraight(self, nums: List[int]) -> bool:
joker = 0
nums.sort()
for i in range(4):
if nums[i] == 0: joker += 1 # 统计大小王数量
elif nums[i] == nums[i+1]: return False # 若有重复,提前返回 False
return nums[4] - nums[joker] < 5 # 最大牌 - 最小牌 < 5 则可以构成顺子
|
class TVBase(object):
"""Абстрактный телевизор"""
def tune_channel(self, channel):
raise NotImplementedError()
class SonyTV(TVBase):
"""Телевизор Sony"""
def tune_channel(self, channel):
print('Sony TV: выбран %d канал' % channel)
class SharpTV(TVBase):
"""Телевизор Sharp"""
... |
__version__ = "1.1.0"
'''
1.1.0
- Base demo module with version info
''' |
#
# PySNMP MIB module CISCOSB-EVENTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-EVENTS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:06:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
# https://leetcode.com/problems/lru-cache/
class Node:
def __init__(self, key, value, nxt=None, prev=None):
self.key = key
self.value = value
self.next = nxt
self.prev = prev
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.map = d... |
#memocate.py: The Trivial Memory Allocator in Python
#Disclaimer: Use this at your own discretion. I am not responsible for anything that happens.
#Author: TD
#initialization
a = "a"
mode = input("(0) Intensive or (1) Safe: ")
#Storing string to memory until overflow.
#Concatenating Runtime: O(n)
if(mode):
print("Saf... |
#
# @lc app=leetcode id=1275 lang=python3
#
# [1275] Find Winner on a Tic Tac Toe Game
#
# @lc code=start
class Solution:
def tictactoe(self, moves: list[list[int]]) -> str:
rows, cols, hill, dale, mark = [0, 0, 0], [0, 0, 0], 0, 0, 1
for i, j in moves:
rows[i] += mark
cols[... |
'''
File: imports.py
Project: src
File Created: Sunday, 28th February 2021 3:10:35 am
Author: Sparsh Dutta (sparsh.dtt@gmail.com)
-----
Last Modified: Sunday, 28th February 2021 3:10:35 am
Modified By: Sparsh Dutta (sparsh.dtt@gmail.com>)
-----
Copyright 2021 Sparsh Dutta
'''
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def geometric_mid(*args):
if args:
ans = 1
for item in args:
ans *= item
return pow(ans, 1/len(args))
else:
return None
if __name__ == "__main__":
print(geometric_mid())
print(geometric_mid(5, ... |
"""
Clothing is a class that represents pieces of clothing in a closet. It tracks the color, category, and clean/dirty state.
"""
class Clothing:
"""
>>> blue_shirt = Clothing("shirt", "blue")
>>> blue_shirt.category
'shirt'
>>> blue_shirt.color
'blue'
>>> blue_shirt.is_clean
True
>>> blue_shirt.wear(... |
# Compute mean of combined data set: combined_mean
combined_mean = np.mean(np.concatenate((bd_1975, bd_2012)))
# Shift the samples
bd_1975_shifted = bd_1975 - np.mean(bd_1975) + combined_mean
bd_2012_shifted = bd_2012 - np.mean(bd_2012) + combined_mean
# Get bootstrap replicates of shifted data sets
bs_replicates_197... |
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2020
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Terce... |
class Solution(object):
def convert_phone(self, phone):
phone = phone.strip().replace(' ', '').replace('(', '').replace(')', '').replace('-', '').replace('+', '')
if len(phone) == 10:
return "***-***-" + phone[-4:]
else:
return "+" + '*' * (len(phone) - 10) + "-***-**... |
"""
Given only a reference to a specific node in a linked list, delete that node from a singly-linked list.
Example:
The code below should first construct a linked list (x -> y -> z) and then delete `y`
from the linked list by calling the function `delete_node`. It is your job to write the `delete_node` function.
""... |
__author__ = "Max Dippel, Michael Burkart and Matthias Urban"
__version__ = "0.0.1"
__license__ = "BSD"
CSConfig = dict()
# SchedulerStepLR
step_lr = dict()
step_lr['step_size'] = (1, 10)
step_lr['gamma'] = (0.001, 0.9)
CSConfig['step_lr'] = step_lr
# SchedulerExponentialLR
exponential_lr = dict()
exponential_lr['ga... |
# [8 kyu] Double Char
#
# Author: Hsins
# Date: 2019/11/28
def two_sort(array):
word = sorted(array)[0]
return "".join(c + '***' for c in word)[0:-3]
|
def func(x,y):
if(y == 0):
return 0
else:
print(x,y)
return x + func(x,y-1)
func(10,10)
|
"""
Factorial of a number
e.g. 4! = 4*3*2*1
"""
def factorial_of_number(num):
if num > 0:
return num * factorial_of_number(num - 1)
else:
return 1
if __name__ == "__main__":
print(factorial_of_number(5))
|
class Person(Thing):
"""A person (alive, dead, undead, or fictional)."""
address: Optional[str] = None
affiliations: Optional[Array["Organization"]] = None
emails: Optional[Array[str]] = None
familyNames: Optional[Array[str]] = None
funders: Optional[Array[Union["Organization", "Person"]]] = No... |
class Solution:
"""
@param nums: a list of integers
@param lower: a integer
@param upper: a integer
@return: return a integer
"""
def countRangeSum(self, nums, lower, upper):
prefixSumCnt = {0: 1}
presum = 0
result = 0
for num in nums:
presum += nu... |
class Params:
# the most important parameter
random_seed = 224422
# system params
verbose = True
device = None # to be set on runtime
num_workers = 2
# dataset params
datasets_dir = 'datasets'
dataset = 'churches'
train_suffix = 'train'
valid_suffix = 'val'
flip = True... |
#
# Example file for working with functions
#
# define a basic function
def func1():
print ("I am a function")
# function that takes arguments
def func2(arg1, arg2):
print (arg1, " ", arg2)
# function that returns a value
def cube(x):
return x*x*x
# function with default value for an argument
def power(num, x... |
class CarrinhoDeCompras: # pode existir sem produtos, mas precisa dos produtos
def __init__(self):
self.__produtos = []
def inserir_produto(self, produto):
self.__produtos.append(produto)
def lista_produto(self):
for produto in self.__produtos:
print(produto.nome, produ... |
name = input("Enter lenght of name: ")
if len(name) < 3:
print("name must be at least 3 characters")
elif len(name) > 50:
print("name can be a maximum of 50 characters")
else:
print("name looks good!")
|
# File: Lists_inside_Dictionary_in_Python.py
# Description: Calculating the scores of sports team by using Lists inside Dictionary
# Environment: PyCharm and Anaconda environment
#
# MIT License
# Copyright (c) 2018 Valentyn N Sichkar
# github.com/sichkar-valentyn
# Reference to:
# [1] Valentyn N Sichkar. Lists... |
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
def filter_iter(list, pred):
filtered = []
for i in list:
if pred(i):
filtered.append(i)
return filtered
def filter_beautiful(list, pred):
return [x for x in list if pred(x)]
def even(x):
return x % 2 == 0
print(filter_iter(my_list, even))
print(filter_beautiful(my_lis... |
"""
986. Interval List Intersections
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two... |
title=xpath("div[@class=BlogTitle]")
urls="http://my\\.oschina\\.net/flashsword/blog/\\d+"
result={"title":title,"urls":urls}
|
print("nihao,shijie")
print("lalalalal")
print("ninniiiinnij")
|
# -*- coding: utf-8 -*-
"""Top-level package for condastats."""
__author__ = """Sophia Man Yang"""
__version__ = '0.1.0'
|
for _ in range(int(input())):
n=int(input())
nums=list(map(int, input().split()))
ini=10**5
for i in range(n):
if ini>nums[i]:
ini=nums[i]
res=i
print(res+1)
|
#
# Copyright (C) 2018 SecurityCentral Contributors see LICENSE for license
#
'''
This base platform module exports platform dependant constants.
'''
class SecurityCentralPlatformBaseConstants(object):
pass
|
expected_output = {
'Et0/2:12': {
'type': 'BD_PORT',
'is_path_list': False,
'port': 'Et0/2:12'
},
'[IR]20012:2.2.2.2': {
'type':'VXLAN_REP',
'is_path_list': True,
'path_list': {
'id': 1191,
'path_count': 1,
'type': 'VXLAN_RE... |
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
class Timeseries:
def __init__(self, col_name, df, date_range=None, min=None, max=None):
self.co... |
nums = input('Please enter 5 numbers, separated by commas:\n')
nums1 = nums.split(',')
#print('You entered ' + nums1[0] + ', ' + nums1[1] + ', ' + nums1[2] + ', ' + nums1[3] + ', ' + nums1[4] + ', ' )
print('You entered ' + nums1[0] + ', ' + nums1[1] + ', ' + nums1[2] + ', ' + nums1[3] + ', ' + nums1[4] +'.')
nums1[... |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... |
class Solution:
def countBits(self, n: int) -> list[int]:
res = []
for i in range(n + 1):
res.append(bin(i).count("1"))
return res
class Solution:
def countBits(self, n: int) -> list[int]:
res = [0] * (n + 1)
for x in range(1, n + 1):
res[x] = re... |
# Used for CSRF protection of wtforms (other than that, the session cookie is not used)
# give a random string, at best generated by import secrets; print(secrets.token_bytes(16))
SECRET_KEY = None
# Used to pepper the hashes of the identifier, just in case there is some information there
PEPPER = b'.\x02G\x04\xc39\xe... |
R1_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.1',
'username': 'user',
'password': 'pass',
}
R2_info = {
'device_type': 'cisco_ios',
'ip': '192.168.1.2',
'username': 'user',
'password': 'pass',
}
R3_info = {
'device_type': 'cisco_ios',
'ip': '1... |
# -*- coding: utf-8 -*-
"""
webelementspy.jsscripts
~~~~~~~~~~~~
This file contain JS scripts to be injected to webdriver
:copyright: (c) 2019 by Yasser.
:license: MIT, see LICENSE for more details.
"""
__all__ = ['js_init', 'js_listner_capture', 'js_raw_html']
js_init = {}
js_init['js_init_init_check'] = r'''
if(d... |
'''
Created on 10/02/2012
@author: Alumno
'''
def suma(x, y):
return x+y
def multiplica(x, y):
return x*y
def cuadrado(x):
return x*x |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/1029/B
n = int(input())
al = list(map(int,input().split()))
cnt = 1
mxc = 0
for i in range(n-1):
if al[i+1]-al[i] <= al[i]:
cnt += 1
else:
if cnt>mxc:
mxc = cnt
cnt = 1
print(max(mxc,cnt))
|
def solve_knapsack(profits, weights, capacity):
if profits is None \
or weights is None \
or len(profits) == 0 \
or len(profits) != len(weights):
return 0
return unbounded_knapsack(profits, weights, capacity, 0)
# We are trying to find the maximum profit
def unboun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.