content stringlengths 7 1.05M |
|---|
# In eg 0.0.x, this file could be used to invoke eg directly, without installing
# via pip. Eg 0.1.x switched to also support python 3. This meant changing the
# way imports were working, which meant this script had to move up a level to be
# a sibling of the eg module directory. This file will exist for a time in orde... |
# from ncats.translator.module.disease.gene import disease_associated_genes
@given('a disease term {disease_identifier} for disease label {disease_label} in Translator Modules')
def step_impl(context, disease_identifier, disease_label):
context.disease = {"disease_identifier":disease_identifier, "disease_label":di... |
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
count=0
for i in range(N):
count+=min(A[i],B[i])
if A[i]<B[i]:
if A[i+1]<B[i]-A[i]:
count+=A[i+1]
A[i+1]=0
else:
count+=B[i]-A[i]
A[i+1]-=B[i]-A[i]
print(count) |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 10:48:08 2019
@author: Wenbin
"""
"""
给定链表1->2->3->4->5->6->7,k = 3,那么旋转后的单链表变为5->6->7->1->2->3->4
"""
class LNode:
def __init__(self , x = 0 , y = None):
self.Data = x
self.Next = y
def ConstructLinkedList(k):
Head = LNode(x... |
def ground_ship(weight):
flat = 20
if weight <= 2:
return weight*1.5 + flat
elif weight > 2 and weight <= 6:
return weight*3.0 + flat
elif weight > 6 and weight <= 10:
return weight*4.0 + flat
else:
return weight*4.75 + flat
cost = ground_ship(8.4)
print(cost)
def drone_ship(weight):
flat ... |
# Copyright 2018 ZTE Corporation.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
def my_func():
print("Foo")
my_other_func = lambda: print("Bar")
my_arr = [my_func, my_other_func]
for i in range (0, 2):
my_arr[i]()
# Bots Position
BOT_POS = [(5401, 1530),(3686, 1857),(3733, 2626),(2325, 1814),
(1718, 1282),(1288, 2418),(1249, 506),(2513,1286)
]
prin... |
class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1 or len(s) <= 2:
return s
# compute the length of the zigzag
zigzagLen = 2*nRows - 2;
lens = len(s)
res = ''
for i in range(nRows):
idx = i
while idx... |
amountNumbers = int(input())
arrNumbers = set(map(int, input().split()))
amountCommands = int(input())
for i in range(amountCommands):
command = input().split()
if command[0] == "pop":
arrNumbers.pop()
elif command[0] == "remove":
if int(command[1]) in arrNumbers:
arrNumbers.r... |
"""Tense analysis and detection related utilities."""
# pylint: disable=E0611
PRESENT = 'PRESENT'
PAST = 'PAST'
FUTURE = 'FUTURE'
MODAL = 'MODAL'
NORMAL = 'NORMAL'
|
# 238. Product of Array Except Self
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
cur, n = 1, len(nums)
out = [1]*n
for i in range(1, n):
cur *= nums[i-1]
out[i] = cur
cur = 1
for i in range(n-2, -1, -1):
... |
try:
myfile1=open("E:\\python_progs\\demochange\\mydir2\\pic1.jpg","rb")
myfile2=open("E:\\python_progs\\demochange\\mydir2\\newpic1.jpg","wb")
bytes=myfile1.read()
myfile2.write(bytes)
print("A new Image is available having name as: newpic1.jpg")
finally:
myfile1.close()
myfile2.close()
|
expected_output = {
'power-usage-information': {
'power-usage-item': [
{
'name': 'PSM 0',
'state': 'Online',
'dc-input-detail2': {
'dc-input-status':
'OK (INP0 feed expected, INP0 feed connected)'
... |
def list3(str):
result = 0
for i in str:
if i == 'a':
result += 1
return result
def main():
print(list3(['Hello', 'world', 'a']))
print(list3(['a', 'a']))
print(list3(['Computational', 'thinking']))
print(list3(['a', 'A', 'A']))
if __name__ == '__main__':
main()
|
"""
CS241 Checkpoint 01A
Written by Chad Macbeth
"""
print("Hello Python World!")
|
# EG8-13 Average Sales
# test sales data
sales=[50,54,29,33,22,100,45,54,89,75]
def average_sales():
'''
Print out the average sales value
'''
total=0
for sales_value in sales:
total = total+sales_value
average_sales=total/len(sales)
print('Average sales are:', average_sales)
aver... |
TRACK_WORDS = ["coronavirus"]
TABLE_NAME = "coronavirus"
TABLE_ATTRIBUTES = "id_str VARCHAR(255), created_at DATETIME, text VARCHAR(255), \
polarity INT, subjectivity INT, user_location VARCHAR(255), \
user_description VARCHAR(255), longitude DOUBLE, latitude DOUBLE, \
retweet_count ... |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
Pub/Sub pattern is a wide used pattern in system design. In this problem, you need to implement a pub/sub pattern to support user subscribes on a specific channel and get notification messages from subscribed channels.
There are 3 methods you need to implement:
subscribe(channel, user_id): Subscribe the given use... |
print ("Hello Guys!") #Hello Guys!
print (2+3) #5
#windows - use F9 key for execution of the selected line
""" learning flow
data types
input from the User
control flow - if else elif
looping - while for
string operations
internal datastructure - list, dict, tuple..
file handling
"""
a = 10
b = 2.3
c = True
d = "Fo... |
'''
1. Write a Python program to find the first triangle number to have over n(given) divisors.
From Wikipedia: A triangular number is a number that is the sum of all of the natural numbers up to a certain number. For example, 10 is a triangular number because 1 + 2 + 3 + 4 = 10. The first 25 triangular numbers are: 1... |
def predict(lr, sample):
return lr.predict(sample.reshape(1, -1))
def predict2(lr, sample):
return lr.predict([sample])
|
class Solution:
def getMoneyAmount(self, n: int) -> int:
# dp[i][j] means minimum amount of money [i , j]
# dp[i][j] = min(n + max(dp[i][n-1] , dp[n+1][j]))
dp = [[-1 for _ in range(n+1)] for _ in range(n+1)]
def cal_range(i,j):
# basic situation
if i >= len(... |
class Question:
def __init__(self, q_text, q_answer):
self._text = q_text
self._answer = q_answer
@property
def text(self):
return self._text
@text.setter
def text(self, d):
self._text = d
@property
def answer(self):
return self._answer
|
# Given a string, find the first uppercase character.
# Solve using both an iterative and recursive solution.
input_str_1 = "lucidProgramming"
input_str_2 = "LucidProgramming"
input_str_3 = "lucidprogramming"
def find_uppercase_iterative(input_str):
for i in range(len(input_str)):
if input_str[i].isupper... |
def phi1(n):
'''
sqrt(n)
'''
res=n
i=2
while(i*i<=n):
if n%i==0:
res=res//i
res=res*(i-1)
while(n%i==0):
n=n//i
i+=1
if n>1:
res=res//n
res=res*(n-1)
return res
'''
log(log(n))
'''
def phi2(maxn)... |
#Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área
#para o usuário.
side = float(input("Informe o tamanho do lado do quadrado: "))
area = pow(side,2)
dbarea = area * 2
print("A area do quadrado eh %.1f e o dobro desta area eh %.1f"%(area,dbarea)) |
"""
Helita python library
"""
__all__ = ["io", "obs", "sim", "utils"]
#from . import io
#from . import obs
#from . import sim
#from . import utils
|
# Given an unsorted integer array, find the smallest missing positive integer.
#
# Example 1:
#
# Input: [1,2,0]
# Output: 3
# Example 2:
#
# Input: [3,4,-1,1]
# Output: 2
# Example 3:
#
# Input: [7,8,9,11,12]
# Output: 1
# Note:
#
# Your algorithm should run in O(n) time and uses constant extra space.
class Solution(... |
def say_(func):
func()
def hi():
print("Hello")
# Estoy pasando hi como argumento de say_
say_(hi)
|
__author__ = 'chris'
"""
Package for holding all of our protobuf classes
"""
|
N, A, B = map(int, input().split())
print(min(A, B), end=" ")
if N - A <= B:
print(B - N + A)
else:
print(0)
|
class Solution:
def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
hashStudent = {0:0, 1:0}
for student in students:
hashStudent[student] += 1
for sandwich in sandwiches:
if hashStudent[sandwich] == 0:
break
... |
def main():
a = 1.0
b = 397.0
print(a/b)
return(0)
main() |
somaidade = 0 #Soma de Todas as Idades
mediaidade = 0 #Média de todas as idades
mih = 0 # Maior idade para Homens
nomev = '' #Nome do Homem Mais velho
totm20 = 0 # Total de Mulheres com Menos de 20 anos
for p in range(1,5):
print(f'-----{p}ª Pessoa-----')
nome = str(input('Nome: ')).strip()
idade = int(inpu... |
class Solution:
def nextGreaterElement(self, n: int) -> int:
num = list(str(n))
i = len(num) - 2
while i >= 0:
if num[i] < num[i + 1]:
break
i -= 1
if i == -1:
return -1
j = len(num) - 1
while num[j] <= nu... |
# 快速排序
def swap(arr, l, r):
temp = arr[l]
arr[l] = arr[r]
arr[r] = temp
def quicksort(arr, l, r):
# 退出条件即为,上一次的小于区的left为本次l的r,单他们重合则必然有序,退出
# rigth同理
if l < r:
p = partition(arr, l, r)
quicksort(arr, l, p[0]-1)
quicksort(arr, p[1]+1, r)
return arr
def partition(arr... |
def cake(candles,debris):
res = 0
for i,v in enumerate(debris):
if i%2:
res+=ord(v)-97
else:
res+=ord(v)
if res>0.7*candles and candles:
return "Fire!"
else:
return 'That was close!' |
class ColorTheme:
def __init__(self, name: str, display_name: str, version: str):
self.name = name
self.display_name = display_name
self.version = version
|
class ProjectStatus:
def __init__(self, name):
self.name = name
self.icon = None
self.status = None
def add_icon(self, icon):
self.icon = icon
def set_status(self, status):
self.status = status
class ProjectStatusDictionary(object):
def __init__(self):
... |
class Vitals:
LEARNING_RATE = 0.1
MOMENTUM_RATE = 0.8
FIRST_LAYER = 5 * 7
SECOND_LAYER = 14
OUTPUT_LAYER = 3 |
# We will register here processors for the message types by name
VM_ENGINE_REGISTER = dict()
def register_vm_engine(engine_name, engine_class):
""" Verifies a message is valid before forwarding it,
handling it (should it be different?).
"""
VM_ENGINE_REGISTER[engine_name] = engine_class |
print('C L A S S I C S O L U T I O N')
range_of_numbers = []
div_by_2 = []
div_by_3 = []
other_numbers = []
for i in range(1,11):
range_of_numbers.append(i)
if i%2 == 0:
div_by_2.append(i)
elif i%3 == 0:
div_by_3.append(i)
else:
other_numbers.append(i)
print('The range of numbe... |
"""
Helper modules.
These should be stand alone modules that could reasonably be their own
PyPI package. This comes with two benefits:
1. The library is void of any business data, which makes it easier to
understand.
2. It means that it is decoupled making it easy to reuse the code in
different sections of the ... |
# limitation :pattern count of each char to be max 1
text = "912873129"
pat = "123"
window_found = False
prev_min = 0
prev_max = 0
prev_pos = -1
lookup_tab = dict()
# detect first window formation when all characters are found
# change window whenever new character was the previous minimum
# if new window smaller t... |
class ResponseKeys(object):
POST = 'post'
POSTS = 'posts'
POST_SAVED = 'The post was saved successfully'
POST_UPDATED = 'The post was updated successfully'
POST_DELETED = 'The post was deleted successfully'
POST_NOT_FOUND = 'The post could not be found'
|
# This problem was recently asked by Google:
# Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Can you get both solutions?
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Function to print the list
def printList... |
# Longest Substring Without Repeating Characters
# Medium
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# DP Solution based on map, not satisfactory.
if not s:
return 0
word_set = {}
... |
"""
========================================================================
Placeholder.py
========================================================================
Author : Shunning Jiang
Date : June 1, 2019
"""
class Placeholder:
pass
|
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/3/10 5:32 PM
# @Author : xiaoliji
# @Email : yutian9527@gmail.com
"""
丑数
>>> nthUglyNumber(5)
5
>>> nthUglyNumber(1)
1
>>> nthUglyNumber(4)
4
>>> nthUglyNumber(1500)
859963392
"""
def nthUglyNumber(n: int) -> int:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def LF_flux(FL, FR, lmax, lmin, UR, UL, dt, dx):
ctilde = dx / dt
return 0.5 * (FL + FR) - 0.5 * ctilde * (UR - UL)
|
"""
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1, 3], [2, 6], [8, 10], [15, 18]], Output: [[1, 6], [8, 10], [15, 18]]
Explanation: Since intervals [1, 3] and [2, 6] overlaps, merge them into [1, 6].
Example 2:
Input: [[1, 4], [4, 5]], Output: [[1, 5]]
Explanation: Interval... |
def get_circles(image):
img = image.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 2, 100)
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for x, y, r in circles:
cv2.circle(img, (x, y), r, ... |
# Ciholas, Inc. - www.ciholas.com
# Licensed under: creativecommons.org/licenses/by/4.0
class Zone:
"""A zone in the form of a polygon"""
def __init__(self, name, vertices, color):
self.name = name
self.vertices = vertices
self.color = color
x_list = []
y_list = []
... |
x, y, w, h = map(int,input().split())
if x >= w-x:
a = w-x
else:
a = x
if y >= h-y:
b = h-y
else:
b = y
if a >= b:
print(b)
else:
print(a)
|
word="I'm a boby, I'm a girl. When it is true, it is ture. that are cats, the red is red."
word = word.replace('.','').replace(',','')
li = word.split()
print(li)
# 第一种方法:
key = set(li)
value = [0 for i in range(len(key))]
dic = {k:v for k,v in zip(key,value)}
print(dic)
for i in dic:
for j in li:
if i ==... |
#3-1 Names
names = ["Jason", "Bob", "James", "Brian", "Marie"]
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4])
#3-2 Greetings
message = " you are a friend"
print(names[0] + message)
print(names[1] + message)
print(names[2] + message)
print(names[3] + message)
print(names[4] + message)
... |
# import pytest
def test_with_authenticated_client(client, django_user_model):
username = "admin"
password = "123456"
django_user_model.objects.create_user(username=username, password=password)
# Use this:
# client.login(username=username, password=password)
response = client.get('/')
asse... |
def setup():
global s, x_count, y_count, tiles, covers
s = 50
x_count = width//s
y_count = height//s
size(800, 600)
tiles = []
covers = []
for x in range(x_count):
tiles.append([])
covers.append([])
for y in range(y_count):
tiles[x].append("... |
#forma de somar comprar de carrinho virtual
carrinho = []
carrinho.append(('Produto 1', 30))
carrinho.append(('Produto 2', '20'))
carrinho.append(('Produto 3', 50))
#no python essa baixo nao eh muito boa
# total = []
# for produto in carrinho:
# total.append(produto[1])
# print(sum(total))
total = sum([float(y)... |
# -*- coding: utf-8 -*-
{
"name": "Import Settings",
"vesion": "10.0.1.0.0",
"summary": "Allows to save import settings to don't specify columns to fields mapping each time.",
"category": "Extra Tools",
"images": ["images/icon.png"],
"author": "IT-Projects LLC, Dinar Gabbasov",
"website": "h... |
room_cost = {
'room for one person': {'cost': 18, 'discount': (0, 0, 0)},
'apartment': {'cost': 25, 'discount': (0.3, 0.35, 0.5)},
'president apartment': {'cost': 35, 'discount': (0.1, 0.15, 0.2)}
}
def discount_index(days_: int) -> int:
if days_ < 10:
return 0
elif 10 <= days_ <= 15:
... |
'''
Utils.py
Spencer Tollefson
November 7, 2018
For use with lebronjames_sentiment_analysis project
'''
def string_clean_df_column(df, col_name):
'''
df: DataFrame which contains the column
col_name: Name of column in DF one wants to perform cleaning operations to
returns: entire DataFrame, with cleane... |
for left in range(7):
for right in range(left,7):
print("[" + str(left) + "|" + str(right) + "]", end=" ")
print
|
class ConnectionInterrupted(Exception):
"""连接中断异常"""
def __str__(self):
error_type = self.__class__.__name__
error_msg = "An error occurred while connecting to redis cluster"
return "Redis Cluster %s: %s" % (error_type, error_msg)
class CompressorError(Exception):
pass
|
"""Exceptions used throughout Eelbrain"""
class DefinitionError(Exception):
"MneExperiment definition error"
class DimensionMismatchError(Exception):
"Trying to align NDVars with mismatching dimensions"
@classmethod
def from_dims_list(cls, message, dims_list):
unique_dims = []
for d... |
number = int(input())
bonus_points = 0
if number <= 100:
bonus_points += 5
elif number > 1000:
bonus_points += number * 0.10
else:
bonus_points += number * 0.20
if number % 2 == 0:
bonus_points += 1
if number % 10 == 5:
bonus_points += 2
print(bonus_points)
print(bonus_points + number) |
def if_hexagon_enabled(a):
return select({
"//micro:hexagon_enabled": a,
"//conditions:default": [],
})
def if_not_hexagon_enabled(a):
return select({
"//micro:hexagon_enabled": [],
"//conditions:default": a,
})
def new_local_repository_env_impl(repository_ctx):
ech... |
DATABASE = '/tmp/tmc2.db'
DEBUG = False
# By default we only listen on localhost. Set this to '0.0.0.0' to accept
# requests from any interface
HOST = '127.0.0.1'
PORT = 5000
# How many quotes per page
PAGE_SIZE = 10
# How should dates be formatted. The format is defined in
# http://arrow.readthedocs.io/en/latest/in... |
# -*- coding: utf-8 -*-
'''
File name: code\lychrel_numbers\sol_55.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #55 :: Lychrel numbers
#
# For more information see:
# https://projecteuler.net/problem=55
# Problem Statement
'''
If we ... |
n,v = map(int,input().split())
mx = -1
for i in range(n):
l,w,h = map(int,input().split())
vo = l*w*h
#print(vo)
if vo>mx: mx = vo
print(mx - v) |
#
# PySNMP MIB module TIARA-IP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIARA-IP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:01 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,... |
#
# PySNMP MIB module HP-ICF-CHAIN (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-CHAIN
# Produced by pysmi-0.3.4 at Wed May 1 13:33:33 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,... |
'''
Missing number in an array
Given an array of size N-1 such that,
it can only contain distinct integers in the range of 1 to N.
Find the missing element.
Example:
Input:
N = 5
A[] = {1,2,3,5}
Output: 4
Input:
N = 10
A[] = {1,2,3,4,5,6,7,8,10}
Output: 9
'''
# Approach-1
'''
We know that sum of N natu... |
# Writing Files in Python
# In order to write to a file, we first open it in write or append mode, after which, we use the python’s f.write() method to write to the file!
# f = open(“this.txt”, “w”)
# f.write(“This is nice”) #Can be called multiple times
# f.close()
f = open('this.txt', 'w')
f.write("dev -... |
#
# PySNMP MIB module CADANT-HW-MEAS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CADANT-HW-MEAS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:45:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
def isPowerOfTwo(x):
return (x != 0) and ((x & (x - 1)))
print(isPowerOfTwo(2))
a = 8
print(bin(a), a)
print(bin(a - 1), a - 1)
print(a & (a - 1))
print(2 & 1, 3 & 1)
# for i in range(6):
# print(i, i& i-1)
# bool isPowerOfTwo(int x)
# {
# // x will check if x == 0 and !(x & (x - 1)) will che... |
class A:
def __init__(self, var=0):
self.var = var
def __str__(self):
return "This is class A"
a = A()
print(a)
"""
All classes are inherited from object class.
> class MyClass:
> pass
>
> print(MyClass.__class__.__bases__)
(<class 'object'>,)
"... |
YT_API_SERVICE_NAME = 'youtube'
DEVELOPER_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
MAX_RESULTS = 50
YT_API_VERSION = 'v3'
LINK = 'https://www.youtube.com/watch?v='
|
"""
info.py - module to store Info class
"""
class Info:
"""
Info - class to store retreived Info from DB
"""
def __init__(self, ids, texts, name = 'Info'):
"""
Infor class constructor
Inputs:
- ids : list of integers
Unique ids for info pieces
- texts : list of texts
Infor texts
"""
self... |
out_data = b"\x1c\x91\x73\x94\xba\xfb\x3c\x30" + \
b"\x3c\x30\xac\x26\x62\x09\x74\x65" + \
b"\x73\x74\x31\x2e\x74\x78\x74\x5e" + \
b"\xc5\xf7\x32\x4c\x69\x76\x65\x20" + \
b"\x66\x72\x65\x65\x20\x6f\x72\x20" + \
b"\x64\x69\x65\x20\x68\x61\x72\x64" + \
... |
# Crie um programa que leia quanto dinheiro uma pessoa
# tem na carteira e mostre quantos Dólares ela
# pode comprar.
# Considere US$ 1.00 = R$ 3.27
d = float(input('Digite quanto tem na carteira: '))
print('Você pode comprar US${:.2f} doláres.'.format(d/3.27))
|
print('-=-' * 20)
print(" LOJA DE COMPRAS BRUCE")
print('-=-' * 20)
compra = float(input('Preço das compras: R$'))
print(''' FORMAS DE PAGAMENTO
[ 1 ] à vista dinheiro/cheque
[ 2 ] à vista cartão
[ 3 ] 2x no cartão
[ 4 ] 3x ou mais no cartão''')
opcao = int(input('Qual é... |
class A():
@staticmethod
def staticMethod():
print("STATIC method fired!")
print("Nothing is bound to me")
print("~"*30)
@classmethod
def classMethod(cls):
print("CLASS method fired!")
print(str(cls)+" is bound to me")
print("~"*30)
# normal method
def normalMethod(self):
print... |
class Solution:
def removeDuplicates(self, S: str) -> str:
def process(S):
lst = []
for key, g in itertools.groupby(S):
n = len(list(g))
if n % 2:
lst.append(key)
return lst
S_lst = list(S)
while True:
... |
class User:
'''
class that generates new instance of user
'''
user_list = []
def __init__ (self, user_name, password):
self.user_name = user_name
self.password = password
def save_user(self):
User.user_list.append(self)
def delete_user(self):
'''
... |
print("Example 05: [The else Statement] \n"
" Print a message once the condition is false")
i = 1
while i < 6:
print(i)
i += 1
else:
print("The condition is false")
|
def isPalindrome(s):
temp = [c for c in s]
temp.reverse()
return ''.join(temp) == s
def twodigit():
return reversed(range(100, 999))
q = reversed(sorted([a * b for a in twodigit() for b in twodigit()]))
found = False
for s in q:
if isPalindrome(str(s)):
print(s)
found = True
break... |
def mutations(inputs):
item_a = set(inputs[0].lower())
item_b = set(inputs[1].lower())
return item_b.intersection(item_a) == item_b
print(mutations(["hello", "Hello"]))
print(mutations(["hello", "hey"]))
print(mutations(["Alien", "line"])) |
while True:
try:
n = int(input("Enter N: "))
except ValueError:
print("Enter correct number!")
else:
if n <= 100:
print("Error: N must be greater than 100!")
else:
for i in range(11, n + 1):
s = i
i = (i-1) + i*i
... |
# PySNMP SMI module. Autogenerated from smidump -f python RUCKUS-SCG-TTG-MIB
# by libsmi2pysnmp-0.1.3
# Python version sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)
# pylint:disable=C0302
mibBuilder = mibBuilder # pylint:disable=undefined-variable,used-before-assignment
# Imports
(Int... |
'''
编写一个函数:
1) 计算所有参数的和的基数倍(默认基数为base=3)
'''
def sumpow(*num,base=3):
sumn=0
for i in num:
sumn+=i
return sumn*base
if __name__=="__main__":
l=[1,2,3]
print(sumpow(*l))
|
class Slot:
def __init__(name, _type=None, item=None):
self.name = name,
if _type is not None:
self.type = _type
else:
self.type = name
self.item = item,
def equip(self):
pass
def unequip(self):
pass
def show(sel... |
def test_modulemap(snapshot):
snapshot.assert_match([1, 2, 4])
def test_runlist():
assert 1 == 1 |
# Charlie Conneely
# Dictionary parser file
def parse(f):
file = open(f, "r")
words = file.read().split()
file.close()
return words
if __name__ == "__main__":
print("please run runner.py instead")
|
def fibonacci(n):
if n == 0:
return (0, 1)
else:
a, b = fibonacci(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
x = 0
y = 0
num = 1
while len(str(x)) < 1000:
x, y = fib... |
def add(x, y):
return x + y
print(add(5, 7))
# -- Written as a lambda --
add = lambda x, y: x + y
print(add(5, 7))
# Four parts
# lambda
# parameters
# :
# return value
# Lambdas are meant to be short functions, often used without giving them a name.
# For example, in conjunction with built-in function map
# ... |
"""
atpthings.util
--------------
Utilities
"""
|
def test_3_5_15(n):
if (n % 15 == 0) and n != 0 :
return 'FizzBuzz'
elif n % 3 ==0 and n != 0:
return 'Fizz'
elif n % 5 == 0 and n != 0:
return 'Buzz'
else:
return n
def coundown():
for x in range (0,101):
print(test_3_5_15(x))
coundown() |
def average(data):
if isinstance(data[0], int):
return sum(data) / len(data)
else:
raw_data = list(map(lambda r: r.value, data))
return sum(raw_data) / len(raw_data)
def minimum(data, index=0):
if index == 0:
data_slice = data
else:
data_slice = data[index:]
return min(data_slice)
def maximum(data, i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.