text stringlengths 37 1.41M |
|---|
# coding=utf-8
# 日期:2020-03-09
# 作者:YangZai
# 功能:函数的定义,调用,形参和实参
# 8-1 消息
def display_message(message):
print(message)
message = '本章学习函数。'
display_message(message)
print()
# 8-2 喜欢的图书
def favorite_book(title):
print('One of my favorite book is ' + title + '.')
favorite_book('Alice in Wonderland')
print()
# 8-3 ... |
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""
class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node':
newNode = Node(insertVal)
if not head:
newNode.next = newNode
r... |
class Solution:
def toLowerCase(self, s: str) -> str:
return "".join([c.lower() if (ord('A') <= ord(c) and ord(c) <= ord('Z')) else c for c in s ]) |
lst = [1,3,5,2,6,4,8,9]
start = 0
for i in range(0,7):
var = []
for i in range(0,3):;
if start == len(lst):
start = 0
var.append(lst[start])
start +=1
print(var)
|
#check whether a number is prime or not.
num = 7
def check_prime(num):
i = 1
count = 0
while i <= num:
if num % i == 0:
print(f"divisible by {i}")
count = count + 1
i = i + 1
if count == 2:
print("prime")
else:
print("Not prime")
if __name_... |
# Method Single Pass Approach
# Time: O(n)
# Space: O(1)
# Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
# If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
# The replacemen... |
# Method 1 DFS recursive
# Time: O(n)
# Space: O(logn)
#
# Given two binary trees, write a function to check if they are equal or not.
#
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#
# Definition for a binary tree node
class TreeNode:
def __init_... |
#Method 1 swap????
#Time O(n)
#Space O(1) inplace
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reorderList(self, head: 'ListNode') -> 'None':
"""
Do not return anything, modify head in-place inst... |
def largest_digit(s):
max_digit = -1
for digit in s:
if digit.isdigit() and int(digit) > max_digit:
max_digit = int(digit)
if max_digit >= 0:
return max_digit
else:
return None
print(largest_digit("sdk2skl")) |
from SEAL.SplineFunction import SplineFunction
from SEAL.lib import create_interpolation_knots, create_cubic_hermite_coefficients, approximate_derivatives
def linear_spline_interpolation(parameter_values, data_values):
"""
Computes the linear spline interpolation to the given
m data points (x_i, y_i).
... |
#ex 3
def f():
name=str(input("Enter Name : "))
age=int(input("Enter age : "))
return 100-age+2021
print("The person turn 100 yrs in "+str(f())) |
texts = input("Enter the string\n")
result = list(filter(lambda x: (x == "".join(reversed(x))), texts))
if len(result)==0:
print("FALSE")
else:
print("TRUE") |
import winsound
frequency = 2500 # Set Frequency To 2500 Hertz
duration1 = 500 # Set Duration To 1000 ms == 1 second
duration2 = 1000 # Set Duration To 1000 ms == 1 second
duration3 = 1500 # Set Duration To 1000 ms == 1 second
#-----------------------------------------------------------------------------------#
# t... |
#Python 3
#Mastermind
#James Moorhead
#CS160
import random
##initiating empty master compare list##
master = []
##initiating empty guess list##
guess = []
##this is computers random start code##
while len(master) <4:
master.append(random.choice(['r','g','b','y']))
##get user input
first =(input('Please... |
q1=int(input())
s=list(map(int,input().split()))
a=[]
for i in s:
a.append(i)
a.sort()
if s==a:
print("yes")
else:
print("no")
|
r=int(input())
p=list(map(int,input().split()))
y=sorted(p,reverse=True)
if y==[0,0,0,0,0]:
print(0)
else:
for i in y:
print(i,end="")
|
import re
def check_password(p):
# print errors if any
num = pwd.isdigit() or type(pwd) is float;
length = len(pwd) < 8;
digits = re.search(r"[0-9]", pwd);
upper = re.search(r"[A-Z]", pwd);
lower = re.search(r"[a-z]", pwd);
error = False;
if num:
print("error: {0} is not string".... |
import matplotlib.pyplot as plt
import numpy as np
def w0(x: np.ndarray, y: np.ndarray):
return y.mean() - w1(x, y)*x.mean()
def w1(x: np.ndarray, y: np.ndarray):
return ((x*y).mean() - x.mean()*y.mean())/((x**2).mean() - x.mean()**2)
def hypothesis(xval, w0, w1):
return w0 + w1*xval
x = np.array([0... |
array1 = [1, 2, 3, 4, 5]
def printArray(thingToPrint):
print(thingToPrint)
for x in thingToPrint:
print(x)
#main
printArray(array1)
|
def indentationExample():
x = 4
if x != 0:
print(str(x))
x = 3
else:
x = 2
|
'''
Pytorch implementation of MLP training on MNIST.
'''
import torch
import torch.nn as nn
hidden_dim = 256
learning_rate = 0.005
class MLP(nn.Module):
def __init__(self, x_dim, hidden_dim, y_dim):
super(MLP, self).__init__()
self.lin1 = nn.Linear(x_dim, hidden_dim)
self.lin2 = nn.L... |
# READ IMAGES - VIDEO - WEBCAM
# 1.2 -> READ VIDEO
import cv2
# For Reading Video we have to create a VideCapture Object in its parameter we give the path of video
# cap = cv2.VideoCapture("Video Location")
cap = cv2.VideoCapture("Resources/abc.mp4")
# Since Video is a Sequence of images we have to use a loop for di... |
digit = input("Enter a number to convert to words: ")
units = {
1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine", 10:"ten", 11:"eleven", 12:"twelve", 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen", 17:"seventeen",
18:"eighteen",19:"nineteen"}
... |
from tkinter import *
class Frame1(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, bg="red")
self.parent = parent
self.widgets()
def widgets(self):
self.text = Text(self)
self.text.insert(INSERT, "Hello World\t")
self.text.insert(END, "This is t... |
class Set(object):
def __init__(self):
self.matches = []
def Clone(self):
s = Set()
s.matches = [m for m in self.matches]
return s
def AddMatch(self, match):
self.matches.append(match)
def Diff(self):
"""
Take all diff values, put them in a list... |
def function1():
print "you chose 1"
def function2():
print "you chose 2"
def function3():
print "you chose 3"
#
# switch is our dictionary of functions
switch = {
'one':function1,
'two':function2,
'three':function3
}
#
#chice can either be 'one', 'two', or 'three
choice = raw_input('Enter one, two, or three: ... |
people = 14
cats = 20
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people >= cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drolled on!"
if people >= dogs:
print "The world is dry!"
dogs +=5
if people >= dogs:
print "People are great... |
import random # import lib to generate random numbers
from urllib import urlopen # import lib to open a URL and get resulting text
import sys #this is so that we can use argv to get passed in arguments
WORD_URL = "http://learncodethehardway.org/words.txt" # set a constant to Zed's URL
WORDS = [] # initialize words lis... |
import sys
import os
from main import ParagraphSearch as pc
if len(sys.argv) <= 3:
print('Too few arguments. At least site, depth and one or more keywords needed.')
if len(sys.argv) >= 5:
print('Too many arguments.')
else:
website = sys.argv[1]
depth = int(sys.argv[2])
keywords = sys.argv[3]
pc.... |
import os
import vdm
# Get a number value from input, or return a default.
def getNumVal(message, default):
n = input(message)
try:
if int(n) < 0:
print("Using default {}".format(default))
return default
return int(n)
except ValueError:
print("Using default {... |
# encoding=utf-8
"""
HJ13 句子逆序
"""
# Get input
input_str = input()
# Split with space and revese
input_list = input_str.split()
input_list.reverse()
# print every word in reversed list
for word_tmp in input_list:
print(word_tmp, end=" ")
|
# encoding=utf-8
"""
HJ3 明明的随机数
"""
# Initial input list
input_list = list()
# Initial input flag and counter
input_flag = True
list_tmp = list()
while input_flag:
# input length at 1st line
try:
len_tmp = input()
if (len_tmp != ""):
# get the length
len_tmp = int(len_... |
#Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes
# are displayed on the 24 h digital clock?
N = int(input("Enter the minutes passed since midnight:"))
hours = (N//60)
minutes = (N%60)
print(f'The hour displayed in the 24 h digital clock is {hours}')
print(f'The mi... |
num=int(input('Enter the number of factorial: '))
product = 1
for i in range(1, num+1):
product= (product * i)
print(f'THe factorial of {num} is {product}')
# Multiplication table (from 1 to 10) in Python
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# Iterate ... |
import random
class Card :
def __init__(self, typeCard, mp, detail):
self.typeCard = typeCard
self.mp = mp
self.detail = detail
def show(self) :
print ("[{}] Mp {} [ Detail : {} ]".format(self.typeCard, self.mp, self.detail))
class Deck :
def __init__(self):
... |
#importing necessary libraries
import numpy as np
from numpy import genfromtxt
from sklearn.neural_network import MLPClassifier
from sklearn import preprocessing, model_selection
# for mean squared error calculation
def mse( y_true, y_pred):
y_err = y_true - y_pred
y_sqr = y_err * y_err
y_sum = np.sum(y_sqr)
... |
from Card import Card
class Deck(object):
card_suit = ["Clubs", "Diamonds", "Hearts", "Spades"]
card_rank = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
def __init__(self):
self.deck = []
self.new_deck()
def __len__(self):
return len(self.de... |
#To find the frequency of each digit(0-9) in a string of alphabets and numbers.
x=str(raw_input("Enter String input :"))
arr=[]
for t in range(0,10):
arr.append(int(0))
for no in range(0,10):
cnt=0
for i in range(0, len(x)):
d=str(no)
if x[i]==d :
cnt+=1
arr[no]=cnt
for t in range(0,10):
print "The ... |
#Python program that matches a word containing 'z or Z', not at start or end of the word. (Example : Aaazwwwiiii is valid and zAswiz is invalid)
import re
pat = '\Bz|Z\B'
word=raw_input("Enter a string :")
def text_match(text):
if re.search(pat, text):
return "Found a match!"
else:
return "Not m... |
#Write a program where a user enters a number n. The program prints the sentence “tell me why I don’t like mondays?” n times. Can the program be written using both types of loops?
limit=input("Enter how many times you want to print the statement :")
count=1
print "The statement is being printed by while loop.."
while... |
#Program to check whether the input string is valid for the given grammar.
import sys
global string,i,l
i=0
l=''
string=''
print """\nGrammar :
A -> B C | D
B -> A E | F\n"""
def A():
global l
if l=='':
getch()
if l=='F':
match('F')
match('C')
A1()
return True
elif l=='D':
match('D')
A1()
return... |
#Write a program where the loop runs from 20 to 10 and print these value.
n=20
for i in range(10,21):
print n
n=n-1
print "The loop is complete."
|
import sys
def hex_to_decimal(my_hex_string):
return str(int(my_hex_string, 16))
if __name__ == '__main__':
filename = "input.txt"
if len(sys.argv) == 2:
filename = sys.argv[1]
f = open(filename, 'r')
for line in f:
print(hex_to_decimal(line.strip()))
f.close()
|
def is_prime(n):
if n == 2 or n == 3:
return True
if n < 2 or not n % 2:
return False
if n < 9:
return True
if not n % 3:
return False
r = int(n ** 0.5)
f = 5
while f <= r:
if not n % f:
return False
if not n % (f+2):
re... |
#-*-coding:utf-8-*-
# number1 = 0
def in_range(n):
# n = 0
if n in range(1,5):
print( '%s is in range' % in_range(n))
else:
print('%s is not in range')
in_range(4)
|
#-*-coding:utf-8-*-
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
self.andy = Employee('andy','green',150000)
def test_give_default_raise(self):
self.andy.give_raise()
self.assertEqual(self.andy.annual_salary,155000)
def tes... |
#-*-coding:utf-8--
a = {'a': 1}
def print_a():
print(a)
def fib(n):
print(1 + 'a')
a, b = 0,1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n):
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
print... |
#!/usr/bin/env python2
# CS 212, hw1-2: Jokers Wild
#
# -----------------
# User Instructions
#
# Write a function best_wild_hand(hand) that takes as
# input a 7-card hand and returns the best 5 card hand.
# In this problem, it is possible for a hand to include
# jokers. Jokers will be treated as 'wild cards' which
# ... |
import matplotlib.pyplot as plt
#matplotlib inline
class Solow:
r"""
Implements the Solow growth model with update rule
k_{t+1} = [(s z k^α_t) + (1 - δ)k_t] /(1 + n)
"""
__slots__ = ['k', 'n', 's', 'z', 'δ', 'α']
def __init__(self, n=0.05, # population growth rate
... |
try :
hoursPrompt = 'Enter hours worked: \n'
hours = int(input(hoursPrompt))
ratePrompt = 'Enter rate: \n'
rate = int(input(ratePrompt))
otHours = 0
pay = 0
if hours <= 40 :
pay = hours * rate
elif hours > 40 :
otHours = hours - 40
pay = rate * 40 +... |
import re
inp = input('Enter a regular expression: ')
count = 0
fhand = open('mbox.txt')
for line in fhand:
if re.search(inp, line): count += 1
print('There are', count, 'matches for', inp, 'in mbox.txt.')
|
def count(word, letter):
number = 0
for index in word:
if index == letter:
number += 1
return number
print(count('banana', 'a'))
|
r=float(input("Input Radius : "))
area=3.14*r*r
perimeter=2*3.14*r
print("Area of Circle: ",area)
print("Perimeter of Circle: ",perimeter)
|
import tkinter as tk
from tkinter import ttk
# initializes the window
root = tk.Tk()
# creates window header
root.title('Calculator')
# output will be show at the top of the GUI
text1 = tk.Text(root,height=1,width=20)
text1.grid(row=0, column=0, columnspan=3,rowspan=1,padx=10,pady=10)
# entry input
entry= tk.Entry... |
import math
import cmath
class MyMath:
_complex = False # Инкапсуляция
pi = 3.14
@classmethod
def get_name(cls):
return cls.__name__ # Инкапсуляция
@staticmethod
def sin(x):
return math.sin(x)
@classmethod
def get_complex(cls):
return cls._complex # Инкапсуляц... |
class Shape:
def __init__(self, width, height):
self.width = width
self.height = height
class Triangle(Shape):
def area(self):
return self.width * self.height / 2
class Rectangle(Shape):
def area(self):
return self.width * self.height
print('Enter width and heigth throug... |
import unittest
import a2
class TestA2(unittest.TestCase):
def test_move_1(self):
"""Test move out of range of the maze"""
maze = a2.Maze([['.','#'],['.','@'],['#','.']], \
a2.Rat('J',1,0), a2.Rat('P',0,0))
actual = maze.move(maze.rat_1,a2.NO_CHANGE,a2.LEFT)
... |
import itertools
"""
Generate n-gram set. With $ appended (prepended) at the end (beginning).
"""
def ngram(word, n):
wordlist = list(word)
k0gram = [''.join(gram) for gram in \
zip(*[wordlist[i:] for i in range(n)])]
if len(k0gram) == 1:
k0gram.append(k0gram[0] + '$')
k0gra... |
#!/usr/bin/python3
"""
This module defines a class Square based on a previous document.
"""
class Square:
"""The Square class defines a square.
Attributes:
None.
"""
def __init__(self, size):
""" Inititialization of the attributes the Square class has.
Args:
size (in... |
#!/usr/bin/python3
""" In this module, testing related to Base class will be done. """
import unittest
import sys
from io import StringIO
from models.square import Square
from models.base import Base
class TestSquare(unittest.TestCase):
""" Test the Square class """
def tearDown(self):
""" Create env... |
#!/usr/bin/python3
"""This module consists of a single function that prints an introduction.
In this module a function called say_my_name is specified and its
functionality consists of saying an specified name and lastname passed
by parameters.
Example:
An example in which the function is implemented is the follo... |
#!/usr/bin/python3
""" In this module, testing related to Base class will be done. """
import unittest
from models.base import Base
class TestBase(unittest.TestCase):
""" Test the base class """
def tearDown(self):
""" Create environment. """
Base.reset_nb()
def test_init(self):
... |
#!/usr/bin/python3
def roman_to_int(roman_string):
decimal = 0
roman_num = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500}
roman_num["M"] = 1000
if roman_string and type(roman_string) == str:
for i in range(len(roman_string)):
if i < len(roman_string) - 1:
... |
#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
square_matrix = []
for i in matrix:
square_matrix.append(list(map(lambda x: x**2, i)))
return square_matrix
|
#!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary:
max_value = max(list(a_dictionary.values()))
for key in a_dictionary.keys():
if a_dictionary[key] == max_value:
return key
return None
|
#Finding Nemo: Family comedy, Animated, main character animal, main character fish
#KungFu Panda: Family Comedy, animated, main character animal, main character likes kungfu
#Secret life of pets: family comedy, animated, main character animal
#Coco: family comedy, animated, main character sings
#Frozen: family comedy, ... |
"""
Search for element d in sorted but rotated array of size n
Return index of elemnt or -1 if not found
[70,71,99,2,12] d=1 => -1 | d=2 => 3 | d=12 => 4 | d=70 => 0 | d=75 => -1 | d=99 => 2 | d=101 => -1
Binary Search
- Check pivot value against leftmost/righmost indexs' value of subarray => sorte... |
#!/usr/bin/env python
import sys
count = 0
java = 0
python = 0
cpp = 0
for line in sys.stdin:
line = line.strip()
language , count = line.split()
count = int(count)
if language == "java":
java += count
if language == "python":
python += count
if language == "c++":
cpp += count
print("java",jav... |
total = 0;
# function returning binary string
def bin_convert(n):
#using bin() for binary conversion
bin1 = bin(n)
# removing "0b" prefix
binary = bin1[2:]
return binary
#function returning palindrome string
def palin(string):
#reversing string using slicing method one step backward
rever... |
import pandas as pd
import smtplib
from tkinter import*
#username and password
username = "your email"
password = "your password"
#read excel
e = pd.read_excel("data file in xls")
emails = e["email"].values
names = e["name"].values
#set smtp
server = smtplib.SMTP("smtp.gmail.com",587)
server.starttls()
#... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import Image
import ImageDraw
def fractal(draw, x, y, r):
if r > 0:
fractal(draw, x-r/2, y-r/2, r/2);
fractal(draw, x-r/2, y+r/2, r/2);
fractal(draw, x+r/2, y-r/2, r/2);
fractal(draw, x+r/2, y+r/2, r/2);
box(draw, x, y, r);
def ... |
import turtle as T
import random
t = T.Turtle()
t.speed(100)
colors = ["blue", "red", "green", "yellow", "black"]
def draw_tree(x):
if(x<10):
return
else:
t.color(random.choice(colors))
t.forward(x)
t.left(30)
draw_tree(3.1*x/4)
t.right(60)
draw_tree(3.... |
import math
def check_prime(n):
i = 2
if n == i:
return 1
while i < int(math.sqrt(n)) + 1:
if n % i == 0:
return 0
i += 1
return 1
def largest_prime_factor(n):
list = []
rootn = int(math.sqrt(n))
for i in range(2, rootn):
if n % i == 0 and check_... |
import math
def check_prime(n):
i = 2
if n == i:
return 1
while i < int(math.sqrt(n)) + 1:
if n % i == 0:
return 0
i += 1
return 1 |
def fib_even_sum(n):
list = [1,2]
sum = 0
while list[-1] < n:
list.append(list[-2] + list[-1])
for i in range(len(list)):
if list[i] < n and i % 3 == 1:
sum += list[i]
return sum
print(fib_even_sum(4000000)) |
#Maia Reynolds
#1/17/18
#inputDemo.py - how to use input
name=input("What is your name? ")
print("Hello",name)
age=int(input("How old are you? "))
print("You are",age+1,"years old")
|
#Maia Reynolds
#1/19/18
#isItaTriangle.py - determines if it could be a triangle
a=float(input("Enter Side A: "))
b=float(input("Enter Side B: "))
c=float(input("Enter Side C: "))
large=max(a,b,c)
smaller=((a+b+c)-large)
print(bool(smaller>large)) |
#Maia Reynolds
#1/24/18
#backwardsBinary.py - converts number to binary
number=int(input("Enter number <256: "))
a=(number//128)*10**7
b=((number%128)//64)*10**6
c=((number%128%64)//32)*10**5
d=(number%128%64%32//16)*10**4
e=(number%128%64%32%16//8)*10**3
f=(number%128%64%32%16%8//4)*10**2
g=(number%128%64%32%16%8%4//... |
import collections
import functools
import cPickle
map = dict()
class Solution(object):
def __init__(self):
self.map = dict()
def coinChange(self, coins, num):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if num in self.map:
... |
balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
totalpaid=0.00
for month in range(1,13):
monthlyinterestrate = annualInterestRate/12.00
monthlypayment = monthlyPaymentRate * balance
unpaidbalance = round((balance - monthlypayment),2)
totalpaid += monthlypayment
balance = round((unpaidbalan... |
##########################
## Anagrams using Python
##########################
str1=input("Enter first string")
str2=input("Enter second string")
if(sorted(str1)==sorted(str2)):
print(str1," and ",str2," are anagrams")
else
print(str1," and ",str2," are not anagrams")
|
#InsertionSort
def InsertionSort(list):
for slicelast in range(len(list)):
pos=slicelast
while ((pos>0) &(list[pos]<list[pos-1])):
(list[pos],list[pos-1])=(list[pos-1],list[pos])
pos=pos-1
print ("InsertionSort over")
#test code
list=[34,45,12,3,67,91,100]
pri... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 11:58:47 2020
JSON in python
@author: Nikhil Bhargava
"""
import json
data='''{
"name":"Nikhil",
"phone":{
"type":"intl",
"number":"+91 991 006 32000"
},
"email":{
"hide":"yes"
}
}
'''
info=json.loads(data)
print('Name: ',info['name'])
print(... |
###
##Python code for Snake and Ladder Game
###
from PIL import Image
import random
end=100
def showBoard():
#slb.jpg is a picture of Snake and Ladded Board
img=Image.open('slb.jpg')
img.show()
def play():
#Get Both players names
p1Name=input("Player 1, Enter your name: ")
p... |
# Write a Python program that asks the user for two numbers.
from tkinter import Tk, messagebox, simpledialog
if __name__ == '__main__':
window = Tk()
window.withdraw()
num1 = simpledialog.askinteger(None, 'Enter a number.')
num2 = simpledialog.askinteger(None, 'Enter another number.')
# Then d... |
#!/usr/bin/env python3
# Part. 1
#=======================================
# Import module
# csv -- fileIO operation
import csv
#=======================================
# Part. 2
#=======================================
# Read cwb weather data
cwb_filename = '107061237.csv'
data = []
header = []
with open(cwb_filena... |
# -*- coding: utf-8 -*-
# The depth of p can also be recursively defined as follows:
# * If pistheroot,thenthedepthof p is 0.
# * Otherwise, the depth of p is one plus the depth of the parent of p.
#
# The height of a position p in a tree T is also defined recursively:
# * If p is a leaf, then the height of p is 0.
# *... |
# -*- coding: utf-8 -*-
# This is exercise of c5.22.
# Develop an experiment to compare the relative efficiency of the extend method
# and the append method. Of course, use these two method to do the same work.
# From the result we can get the conclusion: extend is like about 20 times than
# append method
from timeit i... |
# -*- coding: utf-8 -*-
from array_stack_c6_16 import ArrayStack
from exception import PostfixError
class Postfix(object):
""" evaluate the postfix expression."""
def __init__(self, ps):
self._ps = ps
def _is_number(self, c):
rlt = True
try:
int(c)
except ValueE... |
# -*- coding: utf-8 -*-
#
# the explain of algorithm by stack
# | 1 | x pop
# |-----|
# | 32 | x pop
# |-----| when top item is len one
# | 12 | x pop | 2 | then concate the poped
# |-----... |
# -*- coding: utf-8 -*-
import sys
sys.path.append('..')
from priqueues.heap_priority_queue import HeapPriorityQueue
class PriorityQueue(HeapPriorityQueue):
def _down_heap(self, j):
""" Bubbling the element identified by `j` down."""
while self._has_left(j):
small = self._left(j)
... |
# -*- coding: utf-8 -*-
from circularly_linked_list import CircularlyLinkedList
class CLList(CircularlyLinkedList):
def count_by_loop(self):
if self._tail is None:
return 0
elif self._tail is self._tail._next:
return 1
else:
rlt = 1
walk = se... |
# -*- coding: utf-8 -*-
# This is exercise of p5.33
# Write a Python program for a matrix class that can add and multiply two-
# dimensional arrays of numbers.
class Matrix(object):
def __init__(self, r, c, empty=True):
super(Matrix, self).__init__()
self._row = r
self._column = c
if... |
# -*- coding: utf-8 -*-
def lt(key, other):
""" Compare nonnegative integer key and other base on their binary
expansion."""
if type(key) is not int or type(other) is not int:
raise ValueError('Key and other must both be integer.')
kcopy = key
ocopy = other
kc = oc = 0
while kcopy !... |
# -*- coding: utf-8 -*-
from linked_binary_tree import LinkedBinaryTree
class EulerTour(object):
""" Abstract base class for performing Euler tour of a tree.
_hook_previsit and _hook_postvisit may be overridden by subclasses.
"""
def __init__(self, tree):
""" Prepare an Euler tour template for... |
# -*- coding: utf-8 -*-
from exception import Empty
class TwoColorStack(object):
""" It consists of two stacks—one “red” and one “blue”—and has as its
operations color-coded versions of the regular stack ADT operations.
"""
DEFAULT_CAPACITY = 10
def __init__(self):
super(TwoColorStack, sel... |
# -*- coding: utf-8 -*-
from exception import Empty
class SinglyLinkedList(object):
""" ADT of singly linked list that has a sentinel in the inner
implemetation."""
class _Node(object):
""" Node class for SinglyLinkedList."""
__slot__ = '_element', '_next' # streamline the memory manageme... |
# -*- coding: utf-8 -*-
from random import shuffle
def insert_sort(l):
""" In-palce insert sort."""
walk = 0
while walk < len(l):
i = walk + 1
j = i - 1
while 0 < i < len(l):
if l[i] < l[j]:
tmp = l[i]
l[i] = l[j]
l[j] = t... |
# -*- coding: utf-8 -*-
from transfer_r6_3 import ArrayStack
def reverse_list(l):
s = ArrayStack()
for item in l:
s.push(item)
for i in range(len(l)):
l[i] = s.pop()
if __name__ == '__main__':
l = [i for i in range(10)]
print(l)
reverse_list(l)
print(l)
|
# -*- coding: utf-8 -*-
import sys
sys.path.append('../')
from trees.tree import Tree
class LinkedGeneralTree(Tree):
""" An implementation of general tree by linked structure."""
# nested class
class _Node(object):
""" Lightweight, nonpublic class for storing an element."""
# streamline m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.