text stringlengths 37 1.41M |
|---|
from collections import defaultdict
"""
你可以很方便的使用 collections 模块中的 defaultdict 来构造这样的字典。 defaultdict 的一个特征是它会自动初始化每个 key 刚开始对应的值,所以你只需要 关注添加元素操作了。
"""
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
print(d)
e = defaultdict(set)
e['a'].add(1)
e['a'].add(2)
e['b'].add(4)
print(e)
d = {} # A... |
acl = int(input("Ingrese el # de ACL: "))
if acl >= 1 and acl <= 99:
print("Es una ACL estándar")
elif acl >=100 and acl <= 199:
print("Es una ACL extendida")
else:
print("No es un # de ACL válida")
|
import pronouncing as phones
sentence = input("Enter a sentence to be translated: ")
sentence = sentence.split()
phone_sent = []
for word in sentence:
phone_sent.append(phones.phones_for_word(word))
final_sent = []
for phone_word in phone_sent:
final_sent += phone_word[0].split()
trans_sent = []
def rank_word... |
import numpy as np
class Puzzle:
"""The Puzzle class describes a Sudoku board.
The entries are stored in a numpy array. 0 means no entry, 1-9 mark the corresponding entry.
The indexing convention is as follows: the top-left element on the real sudoku board has index (0, 0). The one below it (1, 0), i.e. t... |
from student import Student
from mentor import Mentor
import time
class CodecoolClass:
"""
This class represents a real class @ Codecool, containing mentors and students working at the class.
Args:
location: stores the city where the the class started
year: stores the year when the class s... |
import string
def to_abc(st: str) -> str:
"""
Функция удаляет все небуквенные символы внутри строки (только латинский алфавит).
:param st: входная строка
:return: выходная строка
"""
st = str(st)
stt = "a"
for i in st:
if i in string.ascii_letters:
stt = stt + i
... |
# Paste your code into this box
balc =balance
monthlyInterestRate = annualInterestRate/12
#minpay=balance/12.0
totalamt= balc * ((1+monthlyInterestRate)**12)
minpay = (balance)/12
while abs(balance) >100:
balance=balc
paid=0
for i in range(12):
paid+=minpay
balance=(1+monthlyInter... |
def printmov(fr,to):
print "move {} from {}".format(fr,to)
def towerstack(n,fr,to,s):
if n==1:
printmov(fr,to)
else:
towerstack(n-1,fr,s,to)
towerstack(1,fr,to,s)
towerstack(n-1,s,to,fr) |
d = {}
x=""
a=int(input())
for i in range(a):
b = input()
c = b.split()
##print (b,c)
avg=float(c[1])+float(c[2])+float(c[3])
##print( c[0],avg)
d["Name"]=c[0]
d["avg"]=avg
x+=c[0]+" "
x+=str(avg)+" "
print(x)
name=x.split()
print(name)
y=input()
for i in name:
if i in y:
... |
#dog class
class dog:
def __init__(self,name):
self.name=name
def sound(self):
print("Boo Boo")
#cat class
class cat:
def __init__(self,name):
self.name=name
def sound(self):
print("Meow Meow")
def makesound(atype):
atype.sound()
stew=dog('stew')
tom=cat('tom')
... |
##inheriting list class
class namedlist(list):
def __init__(self,aname,c=[]):
list.__init__([])
self.a=aname
self.extend(c)
## Adding printout functionality to list
def printout(self):
print(self)
##all methods which work for list will also work for namedlist
a=namedlist(... |
sentence = 'The cat is named Sammy'
print(sentence.upper())
print(sentence.lower())
print(sentence.capitalize())
print(sentence.count('i'))
|
# Example 1
price = input ('How much did you pay? ')
price = float(price)
if price >= 1.00:
tax = .07
else:
tax = 0
print ('Tax rate is: ' + str(tax))
# You can use this simple way in Python 3.X instead of the above strings
price = float(input ('How much did you pay? '))
if price >= 1.00:
tax = .07
else:... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'kgy'
import re
def helloworld():
content = 'Hello 123 4567 World_This is a Regex Demo'
print(len(content))
print(len('abc'))
print(len('呵呵'))
result = re.match('^Hello\s\d\d\d\s\d{4}\s\w{10}', content)
print(result)
print(result... |
# Problem 2
# Assume s is a string of lower case characters.
# Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your
# program should print
# Number of times bob occurs is: 2
|
def countingValleys(n, s):
seaLevel = 0
valeyCount = 0
for str in s:
if str == 'U':
seaLevel += 1
if seaLevel == 0:
valeyCount += 1
elif str == 'D':
seaLevel -= 1
return valeyCount
countingValleys(8, "DDUUUUDD") |
# life.py simulates John Conway's Game of Life with random initial states
# -----------------------------------------------------------------------------
import sys, random, pygame
from pygame.locals import *
# -----------------------------------------------------------------------------
# GLOBALS
# The title and versi... |
line1 = raw_input()
line2 = raw_input()
line1 = list(line1.lower())
line2 = list(line2.lower())
def compare():
for i in range (0, len(line1)):
if line1[i] == line2[i]:
continue
elif line1[i] < line2[i]:
return -1
elif line1[i] > line2[i]:
return 1
re... |
arr = ['lol', 'lola', 'loli']
for ar in arr :
print ('Name of friend : ', ar)
print ('ended') |
'''
QUESTION : Given a number N, print all numbers in the range from 1 to N having
exactly 3 divisors.
'''
import math
def isPrime(num):
if num == 2:
return True
else:
for i in range(2,num):
if (num % i) == 0:
return False
break
... |
# Set item
# ==================================================
fruits = ['apple', 'banana', 'apple', 'pear', 'strawberry']
fruits[3] = 'watermelon'
print(fruits)
fruits[3:5] = 'orange', 'orange'
print(fruits)
# ==================================================
from datetime import date
profile = 'John', 'Adams', d... |
# Vigenere Cipher
'''
Plain text: attackatdawn
Key: python
Cipher text: prmhqxprwhka
We start with a table:
# a b c d e f g h i ...
# ------------------------
# a | b c d e f g h i j ...
# b | c d e f g h i j k ...
# c | d e f g h i j k l ...
# d | e f g h i j h l m ...
# ...
#
In th... |
# .keys(), .values(), .items() methods
# iterating over the dictionary is iteration over its keys
d1 = {'uno': 'one', 'dos': 'two', 'tres': 'three'}
# iteration over the keys
for key in d1:
print(key)
# more obvious iteration over the keys
for key in d1.keys():
print(key)
# If we want to iterate over the values
f... |
# The dictionary contains a set types values
# so items in the set can not be repeated.
# Sets have the same properties as dictionaries.
student_courses = {
'vinnie': {'calculus', 'diff eq'},
'arnold': {'calculus', 'linear algebra'},
'juan luis': {'real analysis'}
}
student_courses['vinn... |
# collections.deque
# ==================================================
def balanced(expr):
groupings = { ')': '(',
']': '[',
'>': '<',
'}': '{', }
stack = []
for char in expr:
if char in groupings.values():
stack.append(char)
elif char in groupings:
if not stack or stack.pop() ... |
# heapq module
# ==================================================
from random import randrange
numbers = [randrange(0, 100) for _ in range(10)]
print(numbers)
# ==================================================
from heapq import heapify
heapify(numbers)
print(numbers)
# ======================================... |
def count_str(s):
return s.count('1', 0)
n = int(input())
cnt = 0
for i in range(1, n + 1, 1):
cnt += count_str(str(i))
print(cnt)
|
r1 = float(input())
r2 = float(input())
r3 = float(input())
R = (r1 + r2 + r3) / 3
print(round(R, 2))
|
import math
n = int(input())
n2 = math.sqrt(n)
flag = 1
for i in range(2, int(n2) + 2, 1):
if n % i == 0:
flag = 0
break
if n == 1:
flag = 0
if flag == 1 or n == 2:
print('yes')
else:
print('no')
|
class mylist(list):
def product(self):
ans = self[0]
for i in self[1:]:
ans *= i
return ans
def __add__(self, other):
if len(self) != len(other):
raise ValueError
ans = mylist()
for i, j in zip(self, other):
ans.app... |
def add_time(start, duration, day_opt = None):
old_time, old_time_meridiem = start.split(" ")
hour, minute = old_time.split(":")
extra_hour, extra_minute = duration.split(":")
# Minute output:
sum_minute = int(minute) + int(extra_minute)
# An extra hour is added to the final output if number ... |
# Adapted from Simple Slalom by Larry Hastings
# http://microbit-micropython.readthedocs.io/en/latest/accelerometer.html
import microbit
import random
# Length and height of display
N = 5
# Accelerometer reading that corresponds to left edge
MIN_ACC = -1024
# Accelerometer reading that corresponds to right edge
MAX... |
import numpy as np
def generate_synthetic_arithmetic_dataset(arithmetic_op, min_value, max_value, sample_size, set_size, boundaries = None):
"""
generates a dataset of integers for the synthetics arithmetic task
:param arithmetic_op: the type of operation to perform on the sum of the two sub sections can... |
#abstraction (encapsulation): hiding inner workings from outside code
#polymorphism: single interface to different types (operate on different objects in the same way)
#inheritance: build functionality off a superclass
#class: a blueprint for an object
#instance: an object created from a class (instantiation)
#construc... |
#FINDING THE LCM
#num1 = int(raw_input("Enter a number: "))
#num2 = int(raw_input("Enter a number: "))
#num3 = num1 * num2
#while num3 >= num1 and num3 >= num2:
# if num3 % num1 == 0 and num3 % num2 == 0:
# x = num3
# num3 -= 1
#print (x)
# #DETERMINING PRIME NUMBERS
#
# num1 = int(raw_input("Enter a ... |
import sys
def main(args):
# args の内容を表示
print('内容 :',args)
# args のタイプを表示
print('タイプ:',type(args))
# args の要素数を表示
print('要素数:',len(args))
# 最初の要素にアクセス
print('-- head --')
print('args[0]:', args[0])
# 最後の要素にアクセス
print('-- tail --')
print('args[-1]:', args[-1])
# 最後に要... |
def main():
x = [ 1.0, 3.0 ] # vector x
a = [ [ .5, .5 ], # matrix A
[ -.5, .5 ] ]
y = [ 0.0 for iRow in range(2) ] # vector y
for irow in range(len(y)): # y = Ax
for icol in range(len(x)):
y[irow] += a[irow][icol] * x[icol... |
def main():
name = input('名前を入力して下さい> ')
age = int(input('年齢を入力して下さい> '))
print('名前:{0} ({1:d}歳)'.format(name,age))
if __name__ == '__main__':
main()
|
def main():
# 文字列(文章)
sentence = 'Rome was not built in a day.'
# 単語リスト(空白区切り)
words = sentence.split(' ')
# 単語の表示
for idx in range(len(words)):
print('{0:d}: {1}'.format(idx,words[idx]))
if __name__ == '__main__':
main()
|
"""
my_complex.py
Copyright (c) 2018-2022, Shogo MURAMATSU, All rights reserved
"""
import math
class MyComplex:
def __init__(self, real, imag):
"""コンストラクタ"""
self.__real = real
self.__imag = imag
def __str__(self):
"""複素数の文字列化"""
sgn = ' - j' if self.__imag < ... |
# Author = Darren Isaacson
# This code will determine your grade
# Enter in score
score = float(input("Enter quiz score"))
# Generates the score grade and displays output
if score >= 90 :
print("A grade")
elif score >= 80 :
print("B grade")
elif score >= 70 :
print("C grade")
elif score >= 60... |
# Author == Darren Isaacson
# This program is designed to change the first letter of a sentence.
def main():
sentences = getSentence()
newList = sentenceSplit(sentences)
getVerfied(newList)
capfirstWord(newList)
def getSentence():
sentence = input("Please enter in the sentence that you... |
# Author = Darren Isaacson
# This program is designed to create loop variation to how what i learned
# Loop which prints all of the numbers between 0 and 5.
print("This output is going to be 0-5")
for loop in range(6):
print(loop)
nextLoop = input("\nEnter to continue to next loop")
# Loop which prin... |
nome = str(input("Digite o nome do novo contato: "))
end = str(input("Digite o endereço do novo contato: "))
rua = str(input("Digite a rua em que o novo contato mora: "))
cep = str(input("Digite o cep do novo contato: "))
bairro = str(input("Digite o bairro do novo contato: "))
estado = str(input("Digite o estado do no... |
database = []
N = int(input())
for _ in range(N):
name, *values= input().split()
index_values = list(map(int, values))
if name == "insert":
database.insert(index_values[0], index_values[1])
elif name == "print":
print(database)
elif name == "remove":
database.remove(index_v... |
students = {}
scores = []
def method_one(scores, students):
scores_min = [x for x in scores if x != min(scores)]
result = []
for key,value in students.items():
if value == min(scores_min):
result.append(key)
return "\n".join(sorted(result))
for _ in range(int(input())):
name = i... |
"""
3、摆放家具
需求:
1).房子有户型,总面积和家具名称列表
新房子没有任何的家具
2).家具有名字和占地面积,其中
床:占4平米
衣柜:占2平面
餐桌:占1.5平米
3).将以上三件家具添加到房子中
4).打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表
"""
'''
类名:房子
属性:户型 总面积 家具列表 可用面积
方法:放家具 放一次家具,可用面积减去放去家具的面积
__str__方法 用来打印房子此时的户型、面积、家具列表、可用面积
类名:家具
属性:家具名称 家具的占地面积
'''
class House(object):
... |
print("Welcome to SmartVAT")
totalPrice = float(input("? = "))
def vatCal(totalPrice):
result = totalPrice+(totalPrice*7/100)
return result
print("Result =", vatCal(totalPrice)) |
import csv
import sys
#CHECK THAT CORRECT NUMBER OF ARGUMENTS GIVEN
if len(sys.argv) != 3:
print 'Invalid call. Please call as follows:'
print 'python test2.py inputfile.csv outputfile.csv'
sys.exit()
#READ IN THE DESTINATION OUTPUT FILENAMES
input_file = sys.argv[1]
output_file = sys.argv[2]
#READ IN THE FILE, C... |
'''
Clone a Graph or create a deepcopy of a Graph
Each node has neighbors
/----A
/ / \
B C
/ \
D E
'''
class Node(object):
def __init__(self, neighbors=None):
self.neighbors = neighbors if neighbors else []
nodeD =... |
"""
Implement Quick Sort recursive
Steps: Follow divide and conquer technique
1) Select mid as pivot (divides the array in 2 parts, left part < pivot and right part > pivot
2) i = 0
3) j = len(array) -1
4) Increment i until array[i] < array[pivot], if greater, then stop
5) Decrement j until array[j... |
'''
Reverse Singly Link List
Algorithm:
1) Create a temporary variable last and current
2) Assign current to head and last = None
3) Loop through end of the link list
new_node = current node
current = current.next
new_node.next = last
last = new_node
'''
from commons.link_l... |
#Write a recursive function to check if a number n is prime
prime = int(input('Input a number:\n'))
def findingprime(prime, F = 3):
if prime < 2:
return False
elif (prime == 3) or (prime == 2):
return True
elif (prime % 2) == 0:
return False
elif (prime % F) == 0:
... |
for k in range(1,11):
print(k,'* x',end='\t\t')
print()
for i in range(1,11):
for j in range(1,11):
print(i*j,end='\t\t\t')
print() |
def numLines(filename):
infile = open(filename,'r')
lineList = infile.readlines()
infile.close()
print('Deze file telt',len(lineList),'regels')
def biggestNum(filename):
infile = open(filename,'r')
content = infile.readlines()
numlist = []
for line in content:
numlist.append(int... |
import sqlite3
from helper_functions import insert_column
con = sqlite3.connect('user_info.db', check_same_thread=False) # Database connection.
c = con.cursor() # Database connection cursor.
num = int(input("How many users do you want to add?: ")) # Number of users to be added to the database.
print("Please enter ... |
#python3
#program mencari korelasi dengan python
import numpy as np
import math
def mean(a):
jml=0
for i in range(len(a)):
jml=jml+a[i]
hasil=jml/len(a)
return hasil
def correl(a,b):
if(len(a)!=len(b)):
print("jumlah data harus sama!")
else:
ma=mean(a)
mb=mean(b)
hasila=0
amin2=0
... |
# Remainder - modular arithmetic
# systematically restrict computation to a range
# long division - divide by a number, we get a quotient plus a remainder
# quotient is integer division //, the remainder is % (Docs)
# problem - get the ones digit of a number
num = 49
tens = num // 10
ones = num % 10
print tens, ones... |
#!/usr/bin/python
'''
Graph and Loss visualization using Tensorboard.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
from PIL import Image... |
def basic (number):
global Rotor
global Motor
global wire
Rotor += 4 *number
Motor += 2 *number
wire += 4.2 *number
def Good (number):
global Rotor
global Motor
global wire
global camera
Rotor +=... |
########################################################################
##
## CS 101
## Program #7
## Name: Colby Chandler
## Email: crcn96@mail.umkc.edu
##
## PROBLEM : getting a word and a range of years to compare word relitivity.
##
## ALGORITHM :
## 1. get both the words that the user want to comp... |
import datetime
import pandas as pd
class InformeCovid():
"""
Esta classe tem como objetivo carregar os informes
da covid do estado do paraná. Ao utilizar a função
carrega_informe() o resultado será um dataframe
com o informe do dia, mes e ano.
Use o método carrega_informe(): para carregar to... |
# tests
import unittest
from compression import compress, decompress
class TestCompression(unittest.TestCase):
def setUp(self):
"""setup list of tuples (first, second)
such that second is expected output of compress(first)"""
self.toTestList = [('',''),('A','A'),('AA','AA0'),('AAA','AA1'),
('AAAA', 'AA2... |
from numpy import sqrt
from numpy import asarray
class Frame(object):
"""Defines a Lorentz transform between reference frames."""
def __init__(self, beta=0.0):
"""`beta` is velocity of moving frame as a fraction of c."""
self.beta = beta
@property
def gamma(self):
"""T... |
'''
Given a non-negative integer n, write a function to_binary/ToBinary which returns that number in a binary format.
to_binary(1) # should return 1
to_binary(5) # should return 101
to_binary(11) # should return 1011
'''
# def to_binary(n):
# return int(bin(n)[2:])
def to_binary(n):
return int(f'{n:b}')
... |
def romanToInt(s):
d={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
letters=["I","V","X","L","C","D","M"]
num=0
for i in range(len(s)):
if s[i] not in letters:
break
val=d[s[i]]
if i!=0 and d[s[i]]>d[s[i-1]]:
val=val-d[s[i-1]]*2
num=num+val
... |
# def reverseString(s): # O(N) complexity
# """
# Takes a string and reverses it.
# Do not return anything, modify s in-place instead.
# """
# l=len(s)
# for i in range(l//2):
# s[i],s[l-i-1]=s[l-i-1],s[i] #swapping letters
# return s
def r... |
def reverseVowels(s): # O(N) complexity
"""
Given a string s, reverse only all the vowels in the string and return it.
"""
temp=""
vows=""
vowels="aeiou"
for i in s:
if i.lower() in vowels: #extracting the vowels
vows=i+vows
c=0
for i in s:
... |
'''write out a for loop that takes in from and to
and from there confirm if the index is less than zero
then append each word to a from to category and if
we find the last index in the list then we stop'''
def get_order(tickets):
order = []
from_to_dictionary = {}
#build dictionary from and to
for tic... |
import string
import random
from textwrap import wrap
def charset(length: int = 6) -> str:
return ''.join(random.choices(string.ascii_lowercase, k=length))
def superset(
length: int = 3,
set_length: int = 6,
numbers: int = 1,
uppercase: int = 1,
separator: str = '-'
) -> str:
assert numb... |
# 方法1
#!/usr/bin/python
# -*- coding:utf-8 -*-
a = int(input('摄氏度转换为华氏温度请按1\n华氏温度转化为摄氏度请按2\n'))
while a != 1 and a != 2:
a = int(input('你选择不正确,请重新输入。\n摄氏度转换为华氏温度请按1\n华氏温度转换为摄氏度请按2\n'))
if a == 1:
celsius = float(input('输入摄氏度:'))
fahrenheit = (celsius*1.8)+32 #计算华氏温度
print('%.1f摄氏度转为华氏温度为%.1f' %(celsius... |
# 如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。 例如1^3 + 5^3 + 3^3 = 153。
# 1000以内的阿姆斯特朗数: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407。
# 以下代码用于检测用户输入的数字是否为阿姆斯特朗数:
# Filename : test.py
# author by : www.runoob.com
# Python 检测用户输入的数字是否为阿姆斯特朗数
# 获取用户输入的数字
num = int(input("请输入一个数字: "))
# 初始化变量 sum
sum = 0
# 指数
n = len(str... |
# str.format() 的基本使用如下:
print('{}网址: "{}!"'.format('菜鸟教程', 'www.runoob.com'))
# 括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换。
# 在括号中的数字用于指向传入对象在 format() 中的位置,如下所示:
print('{0} 和 {1}'.format('Google', 'Runoob'))
print('{1} 和 {0}'.format('Google', 'Runoob'))
# 如果在 format() 中使用了关键字参数, 那么它们的值会指向使用该名字的参数。
print('{name}网址: {si... |
# 方法1
# 最小公倍数
def lcm(a, b):
if b > a:
a, b = b, a # a为最大值
if a % b == 0:
return a # 判断a是否为最小公倍数
mul = 2 # 最小公倍数为最大值的倍数
while a*mul % b != 0:
mul += 1
return a*mul
while(True):
a = int(input("Input 'a':"))
b = int(input("Input 'b':"))
print... |
def getUserInput():
while True:
try:
firstStock = \
list(map(int,
input("Enter your 1st list of stock prices separated by space: ").strip().split()))
size_limit = all(i in range(1, 1001) for i in firstStock)
n_days = len(firstStoc... |
# GLOBAL VARIABLES
# if game is still going on :
game_still_going = True
# who's the player?
current_player = "X"
# winner?
winner = None
# GAME BOARD
board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
# DISPLAY THE BOARD
def display_board():
print(board[0] + " | " + board[1] + " | " + boa... |
# class is the keyword then name of the class
# Creating an Animal class
class Animal():
# name = "Dog" # class variable
def __init__(self): # self refers to the current class
self.alive = True #attributes/ variables
self.spine = True
self.lungs = True
def move(self):
retur... |
s="jay"
print(s)
print(s.capitalize())
#this does not changes the actual string but returns a new string because string is immutable
x="babble"
print(x[0]+ x[1:].replace(s[0],'*'))
#write a program to accept a string from user and jumble it in such a way that from the beginnign are considered in first part and secon... |
#WAP to accpet a foldername from user and create a zip file out of it.(hint= import shutil)
from shutil import make_archive
import os
input=eval(input("Enter the file name"))
make_archive(input, 'gztar')
#make_archive is a method from shtuil library in which first argument is input file name with destination... |
#WAP to acccpet number and number of bits to turn ON from given position.(hint: use OR and just shift without compliment)
'''
def Bitwise(no1,nbit,pos):
x=(1<<nbit)-1
x=x<<(pos-nbit)
return no1|x
def main():
no1=eval(input("Enter the number"))
bit,pos=eval(input("Enter number of bits and postion... |
#Homework:Write a program to accept a file name from user and print all verbs in it.
import re
def VerbsInFile(input_file):
try:
fd=open(input_file)
fs=open("verbs.txt","w")
regex_verbs=re.compile(r"(\w+)(ing\b)|(\w+)(ly\b) ")
data=fd.read()
for i in regex_verbs.finditer(data):
print(i.group(0))
fs.wri... |
def Set_Operation (input_list1, input_list2):
Set_intersection (input_list1, input_list2)
Set_union(input_list1,input_list2)
Set_SymmetricDifference(input_list1,input_list2)
def Set_SymmetricDifference(input_list1,input_list2):
output_list3=[]
for x in input_list1:
if x not in i... |
#WAP to accept a list of integer from user and check if its palindrome or not.
def List_Palindrome(input_list):
i=0
j=-1
while i<len(input_list):
if input_list[i]==input_list[j]:
i=i+1
j=j-1
else:
break
if i==len(input_list):
return... |
"""Question 1.9
Given an is_substring function, write a function which determines if a string is a rotation of another string
by only calling is_substring once
"""
def is_string_rotation(s1, s2):
"""Determines if a string is a rotation of another, O(N)
Args:
s1: the string
s2: possible ro... |
import unittest
from data_structures.c4_trees_and_graphs.structures.trie import Trie
class TestTrie(unittest.TestCase):
def test_insert_raises_ValueError_if_key_contains_non_lowercase_ascii_characters(self):
with self.assertRaises(ValueError):
Trie().insert('abCd')
def test_insert_insert... |
"""Question 4.5
Implement a function to check whether a binary tree is a binary search tree
"""
def is_binary_search_tree(tree, min_data = None, max_data = None):
"""
Args:
tree: TreeNode to validate
min_data: lower threshold to check
max_data: higher threshold to check
Returns:
... |
"""Question 3.3
Implement a set of stacks where a new stack is start once capacity is met. Should behave like a normal stack.
"""
from data_structures.c3_stacks_and_queues.stack import Stack
class StackWithSize(Stack):
def __init__(self):
super().__init__()
self.size = 0
def push(self, data)... |
"""Question 2.4
Delete a node in the middle of a singly linked list, given only access to that node"""
def delete_middle_node(node):
"""Removes the a node from a linked list
Args:
node: the node to remove
Returns:
boolean representing success
"""
if node is None or node.next is No... |
"""
initials.py - San Kwon
Initials More
This program prints a given name's initials.
"""
# ask for name and get rid of spaces in the front and back
name = input("")
name = name.strip()
# find initials
initials = ""
while name.find(" ") != -1:
initials = initials + name[0].upper()
space = name.find(" ")
n... |
import pandas as pd
import numpy as np
class gnb:
"""Implementation of a Gaussian Naive Bayes classifier built on top of pandas.
To use this class, first create an instance, fit the model, then use the predict function to classify additional data.
```Python
classifier = gnb()
data = pd.DataFrame(... |
from functools import wraps
def out(func):
@wraps(func)
def decorated(self):
square = func(self)
if square.is_out_of_board():
return None
return square
return decorated
class Square():
def __init__(self, x, y):
self.x = x
self.y = y
self.tu... |
from collections import defaultdict
import re
from math import sqrt
import json
def remove_punctuation(text):
return re.sub('[,.?";:\-!@#$%^&*()]', '', text)
def remove_common_words(text_vector):
"""Removes 50 most common words in the uk english.
source: http://www.bckelk.ukfsn.org/words/uk1000n.h... |
"""
Demonstração da utilização simples dos métodos HTTP
Métodos HTTP
GET
Sends data in unencrypted form to the server.
Most common method.
HEAD
Same as GET, but without response body.
POST
Used to send HTML form data to server. Data received by POST
method is not c... |
"""
Oferece um vetor matemático e operações de vetor
>>> v = Vetor(x=10, y=5)
>>> v.x == v[0] == 10
True
>>> v.y == v[1] == 5
True
"""
from collections import namedtuple
Vetor = namedtuple('Vetor', ['x', 'y'])
def soma_vetor(v1, v2):
"""
Retorna um vetor que representa a soma dos vetores v1 e v2 (v1 + v2)... |
# -*- coding: utf-8 -*-
"""
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def createLinkedList(list):
root = cur = None
for i in list:
if root == None:
... |
#encoding:utf-8
# __author__ = 'donghao'
# __time__ = 2019/3/19 14:16
class Person(object):
def __init__(self,value):
self.firstname = value
# getter function
@property
def firstname(self):
return self._firstname
@firstname.setter
def firstname(self,value):
self._first... |
#encoding:utf-8
# __author__ = 'donghao'
# __time__ = 2019/1/13 14:38
# 1.创建异常exception对象
# 2.使用raise关键字 抛出异常
def func():
pass_word = input('请输入密码')
if len(pass_word) > 8:
return pass_word
raise Exception('密码长度错误')
try:
print(func())
except Exception as result:
print(result)
|
#encoding:utf-8
class Person(object):
def __init__(self,num):
self.num = num
def __add__(self, other):
return Person(self.num+other.num)
def __str__(self):
return 'num='+str(self.num)
per1 = Person(1)
per2 = Person(56)
# print(per1+per2) #=per1._add_(per2)
print(per1.__add__(per... |
# encoding:utf-8
# __author__ = 'donghao'
# __time__ = 2019/3/23 18:52
# 该模式虽名为修饰器,但这并不意味着它应该只用于让产品看起来更漂亮。修饰器模式通常用于扩展一个对象的功能。
# 这类扩展的实际例子有,给枪加一个消音器、使用不同的照相机镜头
def before(func): # 定义修饰器
def wrapper(*args, **kwargs): # 新函数
print('Before function called.') # 新增的语句
return func(*args, **kwargs) # ... |
#encoding:utf-8
'''
类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例
类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
数据成员:类变量或者实例变量, 用于处理类及其实例对象的相关的数据。
方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
实例变量:定义在方法中的变量,只作用于当前实例的类。
继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.