l1 = [] # This is an empty list
t1 = () # Create an empty tuple
t1
l2 = [1,3,5]
t2 = (1, 3, 5) # Create a tuple with three elements
t2
l2[1] = 7
l2
t2
t2[1] = 77
# Create a tuple from a list
t3 = tuple([2 * x for x in range(1, 5)])
t3
# Create a tuple from a string
t4 = tuple("abac") # t4 is ('a', 'b', 'a', 'c’)
t4
tuple1 = ("green", "red", "blue") # Create a tuple
print(tuple1)
tuple2 = tuple([7, 1, 2, 23, 4, 5]) # Create a tuple from a list
print(tuple2)
print("length is", len(tuple2)) # Use function len
print("max is", max(tuple2)) # Use max
print("min is", min(tuple2)) # Use min
print("sum is", sum(tuple2)) # Use sum
print("The first element is", tuple2[0]) # Use indexer
tuple3 = tuple1 + tuple2 # Combine 2 tuples
print(tuple3)
tuple3 = 2 * tuple1 # Multiple a tuple
print(tuple3)
print(tuple2[2 : 4]) # Slicing operator
print(tuple1[-1])
print(2 in tuple2) # in operator
for v in tuple1:
print(v, end = " ")
print()
list1 = list(tuple2) # Obtain a list from a tuple
list1.sort()
tuple4 = tuple(list1)
tuple5 = tuple(list1)
print(tuple4)
print(tuple4 == tuple5) # Compare two tuples
# SETS:
s1 = set() # Create an empty set
print(s1)
s2 = {1, 3, 5} # Create a set with three elements
print(s2)
s3 = set([1, 3, 5]) # Create a set from a tuple
print(s3)
# Create a set from a list
s4 = set([x * 2 for x in range(1, 10)])
print(s4)
# Create a set from a string
s5 = set("abac") # s5 is {'a', 'b', 'c'}
print(s5)
set6 = {1,3,5,5,1,1,4}
print(set6)
set6.add(8)
set6
set6.add(3)
set6
set1 = {"green", "red", "blue", "red"} # Create a set
print(set1)
set2 = set([7, 1, 2, 23, 2, 4, 5]) # Create a set from a list
print(set2)
print("Is red in set1?", "red" in set1)
print("length is", len(set2)) # Use function len
print("max is", max(set2)) # Use max
print("min is", min(set2)) # Use min
print("sum is", sum(set2)) # Use sum
set3 = set1 | {"green", "yellow"} # Set union
print(set3)
set3 = set1 - {"green", "yellow"} # Set difference
print(set3)
set3 = set1 & {"green", "yellow"} # Set intersection
print(set3)
set3 = set1 ^ {"green", "yellow"} # Set exclusive or
print(set3)
list1 = list(set2) # Obtain a list from a set
print(set1 == {"green", "red", "blue"}) # Compare two sets
set1.add("yellow")
print(set1)
set1.remove("yellow")
print(set1)
import random
import time
NUMBER_OF_ELEMENTS = 50000
# Create a list
lst = list(range(NUMBER_OF_ELEMENTS))
random.shuffle(lst)
# Create a set from the list
s = set(lst)
# Test if an element is in the set
startTime = time.time() # Get start time
for i in range(NUMBER_OF_ELEMENTS):
i in s
endTime = time.time() # Get end time
runTime = int((endTime - startTime) * 1000) # Get test time
print("To test if", NUMBER_OF_ELEMENTS,
"elements are in the set\n",
"The runtime is", runTime, "milliseconds")
# Test if an element is in the list
startTime = time.time() # Get start time
for i in range(NUMBER_OF_ELEMENTS):
i in lst
endTime = time.time() # Get end time
runTime = int((endTime - startTime) * 1000) # Get test time
print("\nTo test if", NUMBER_OF_ELEMENTS,
"elements are in the list\n",
"The runtime is", runTime, "milliseconds")
# Remove elements from a set one at a time
startTime = time.time() # Get start time
for i in range(NUMBER_OF_ELEMENTS):
s.remove(i)
endTime = time.time() # Get end time
runTime = int((endTime - startTime) * 1000) # Get test time
print("\nTo remove", NUMBER_OF_ELEMENTS,
"elements from the set\n",
"The runtime is", runTime, "milliseconds")
# Remove elements from a list one at a time
startTime = time.time() # Get start time
for i in range(NUMBER_OF_ELEMENTS):
lst.remove(i)
endTime = time.time() # Get end time
runTime = int((endTime - startTime) * 1000) # Get test time
print("\nTo remove", NUMBER_OF_ELEMENTS,
"elements from the list\n",
"The runtime is", runTime, "milliseconds")
def main():
# Prompt the user to enter a file
filename = input("Enter a filename: ").strip()
infile = open(filename, "r") # Open the file
wordCounts = {} # Create an empty dictionary to count words
for line in infile:
processLine(line.lower(), wordCounts)
pairs = list(wordCounts.items()) # Get pairs from the dictionary
items = [[count, word] for (word, count) in pairs]
items.sort(reverse = True) # Sort pairs in items
for count, word in items[ : 100]: # Slice the first 10 items
print(word, count, sep = '\t')
# Count each word in the line
def processLine(line, wordCounts):
line = replacePunctuation(line) # Replace punctuation with space
words = line.split() # Get words from each line
for word in words:
if word in wordCounts:
wordCounts[word] += 1
else:
wordCounts[word] = 1 # Add an item in the dictionary
# Replace punctuation in the line with space
def replacePunctuation(line):
for ch in line:
if ch in "~@#$%^&*()_-+=~<>?/,.;:!{}[]|'\"":
line = line.replace(ch, " ")
return line
main() # Call the main function
s7 = "Get pairs from the dictionary"
s7.split()
def main():
n = eval(input("Enter a nonnegative integer: "))
print("Factorial of", n, "is", factorial(n))
# Return the factorial for a specified number
def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
main() # Call the main function
Enter a nonnegative integer: 5 Factorial of 5 is 120
def main():
n = eval(input("Enter a nonnegative integer: "))
print("Factorial of", n, "is", factorial(n))
# Return the factorial for a specified number
def factorial(n):
if n == 0: # Base case
return 1
else:
rcall = factorial(n - 1) # Recursive call
print("n=",n," rcall=",rcall)
return n * rcall
main() # Call the main function
Enter a nonnegative integer: 5 n= 1 rcall= 1 n= 2 rcall= 1 n= 3 rcall= 2 n= 4 rcall= 6 n= 5 rcall= 24 Factorial of 5 is 120
def main():
index = eval(input("Enter an index for a Fibonacci number: "))
# Find and display the Fibonacci number
print("The Fibonacci number at index", index, "is", fib(index))
# The function for finding the Fibonacci number
def fib(index):
if index == 0: # Base case
return 0
elif index == 1: # Base case
return 1
else: # Reduction and recursive calls
return fib(index - 1) + fib(index - 2)
main() # Call the main function
Enter an index for a Fibonacci number: 25 The Fibonacci number at index 25 is 75025
def nPrintln(message, times):
if times >= 1:
print(message, times)
nPrintln(message, times - 1)
# The base case is times == 0
nPrintln("Hello", 6)
Hello 6 Hello 5 Hello 4 Hello 3 Hello 2 Hello 1
def isPalindrome1(s):
if len(s) <= 1: # Base case
return True
elif s[0] != s[len(s) - 1]: # Base case
return False
else:
return isPalindrome(s[1 : len(s) - 1])
s1 = "madam"
isPalindrome(s1)
True
s1 = "omadam"
isPalindrome(s1)
False
def isPalindrome2(s):
return isPalindromeHelper(s, 0, len(s) - 1)
def isPalindromeHelper(s, low, high):
if high <= low: # Base case
return True
elif s[low] != s[high]: # Base case
return False
else:
return isPalindromeHelper(s, low + 1, high - 1)
s1 = "madam"
isPalindrome1(s1)
True
def sort(lst):
sortHelper(lst, 0, len(lst) - 1) # Sort the entire lst
def sortHelper(lst, low, high):
if low < high:
# Find the smallest number and its index in lst[low .. high]
indexOfMin = low;
min = lst[low];
for i in range(low + 1, high + 1):
if lst[i] < min:
min = lst[i]
indexOfMin = i
# Swap the smallest in lst[low .. high] with lst[low]
lst[indexOfMin] = lst[low]
lst[low] = min
# Sort the remaining lst[low+1 .. high]
print(lst)
sortHelper(lst, low + 1, high)
def main():
lst = [3, 2, 1, 5, 9, 0]
sort(lst)
print(lst)
main()
[0, 2, 1, 5, 9, 3] [0, 1, 2, 5, 9, 3] [0, 1, 2, 5, 9, 3] [0, 1, 2, 3, 9, 5] [0, 1, 2, 3, 5, 9] [0, 1, 2, 3, 5, 9]
def recursiveBinarySearch(list, key):
low = 0
high = len(list) - 1
return recursiveBinarySearchHelper(list, key, low, high)
def recursiveBinarySearchHelper(list, key, low, high):
if low > high: # The list has been exhausted without a match
return -low - 1
mid = (low + high) // 2
print("mid index", mid, " Value=", list[mid])
if key < list[mid]:
return recursiveBinarySearchHelper(list, key, low, mid - 1)
elif key == list[mid]:
return mid
else:
return recursiveBinarySearchHelper(list, key, mid + 1, high)
def main():
list = [3, 5, 6, 8, 9, 12, 34, 36]
print(recursiveBinarySearch(list, 12))
print(recursiveBinarySearch(list, 4))
main()
mid index 3 Value= 8 mid index 5 Value= 12 5 mid index 3 Value= 8 mid index 1 Value= 5 mid index 0 Value= 3 -2
def main():
n = eval(input("Enter number of disks: "))
# Find the solution recursively
print("The moves are:")
moveDisks(n, 'A', 'B', 'C')
# The function for finding the solution to move n disks
# from fromTower to toTower with auxTower
def moveDisks(n, fromTower, toTower, auxTower):
if n == 1: # Stopping condition
print("Move disk", n, "from", fromTower, "to", toTower)
else:
moveDisks(n - 1, fromTower, auxTower, toTower)
print("Move disk", n, "from", fromTower, "to", toTower)
moveDisks(n - 1, auxTower, toTower, fromTower)
main() # Call the main function
Enter number of disks: 4 The moves are: Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C Move disk 4 from A to B Move disk 1 from C to B Move disk 2 from C to A Move disk 1 from B to A Move disk 3 from C to B Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B
from tkinter import * # Import tkinter
class SierpinskiTriangle:
def __init__(self):
window = Tk() # Create a window
window.title("Sierpinski Triangle") # Set a title
self.width = 200
self.height = 200
self.canvas = Canvas(window,
width = self.width, height = self.height)
self.canvas.pack()
# Add a label, an entry, and a button to frame1
frame1 = Frame(window) # Create and add a frame to window
frame1.pack()
Label(frame1,
text = "Enter an order: ").pack(side = LEFT)
self.order = StringVar()
entry = Entry(frame1, textvariable = self.order,
justify = RIGHT).pack(side = LEFT)
Button(frame1, text = "Display Sierpinski Triangle",
command = self.display).pack(side = LEFT)
window.mainloop() # Create an event loop
def display(self):
self.canvas.delete("line")
p1 = [self.width / 2, 10]
p2 = [10, self.height - 10]
p3 = [self.width - 10, self.height - 10]
self.displayTriangles(int(self.order.get()), p1, p2, p3)
def displayTriangles(self, order, p1, p2, p3):
if order == 0: # Base condition
# Draw a triangle to connect three points
self.drawLine(p1, p2)
self.drawLine(p2, p3)
self.drawLine(p3, p1)
else:
# Get the midpoint of each triangle's edge
p12 = self.midpoint(p1, p2)
p23 = self.midpoint(p2, p3)
p31 = self.midpoint(p3, p1)
# Recursively display three triangles
self.displayTriangles(order - 1, p1, p12, p31)
self.displayTriangles(order - 1, p12, p2, p23)
self.displayTriangles(order - 1, p31, p23, p3)
def drawLine(self, p1, p2):
self.canvas.create_line(
p1[0], p1[1], p2[0], p2[1], tags = "line")
# Return the midpoint between two points
def midpoint(self, p1, p2):
p = 2 * [0]
p[0] = (p1[0] + p2[0]) / 2
p[1] = (p1[1] + p2[1]) / 2
return p
SierpinskiTriangle() # Create GUI
<__main__.SierpinskiTriangle at 0x25fa06ea5b0>
from tkinter import * # Import tkinter
SIZE = 8 # The size of the chessboard
class EightQueens:
def __init__(self):
self.queens = SIZE * [-1] # Queen positions
self.search(0) # Search for a solution from row 0
# Display solution in queens
window = Tk() # Create a window
window.title("Eight Queens") # Set a title
image = PhotoImage(file = "image/queen.gif")
for i in range(SIZE):
for j in range(SIZE):
if self.queens[i] == j:
Label(window, image = image).grid(
row = i, column = j)
else:
Label(window, width = 5, height = 2,
bg = "red").grid(row = i, column = j)
window.mainloop() # Create an event loop
# Search for a solution starting from a specified row
def search(self, row):
if row == SIZE: # Stopping condition
return True # A solution found to place 8 queens
for column in range(SIZE):
self.queens[row] = column # Place it at (row, column)
if self.isValid(row, column) and self.search(row + 1):
return True # Found and exit for loop
# No solution for a queen placed at any column of this row
return False
# Check if a queen can be placed at row i and column j
def isValid(self, row, column):
for i in range(1, row + 1):
if (self.queens[row - i] == column # Check column
or self.queens[row - i] == column - i
or self.queens[row - i] == column + i):
return False # There is a conflict
return True # No conflict
EightQueens() # Create GUI
<__main__.EightQueens at 0x25fa16d0370>
import turtle
def tree(branchLen,t):
if branchLen > 5:
t.forward(branchLen)
t.right(20)
tree(branchLen-15,t)
t.left(40)
tree(branchLen-15,t)
t.right(20)
t.backward(branchLen)
def main():
t = turtle.Turtle()
myWin = turtle.Screen()
t.left(90)
t.up()
t.backward(100)
t.down()
t.color("green")
tree(75,t)
myWin.exitonclick()
main()
try:
turtle.bye()
except:
print("bye")
import turtle
def drawTriangle(points,color,myTurtle):
myTurtle.fillcolor(color)
myTurtle.up()
myTurtle.goto(points[0][0],points[0][1])
myTurtle.down()
myTurtle.begin_fill()
myTurtle.goto(points[1][0],points[1][1])
myTurtle.goto(points[2][0],points[2][1])
myTurtle.goto(points[0][0],points[0][1])
myTurtle.end_fill()
def getMid(p1,p2):
return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2)
def sierpinski(points,degree,myTurtle):
colormap = ['blue','red','green','white','yellow',
'violet','orange']
drawTriangle(points,colormap[degree],myTurtle)
if degree > 0:
sierpinski([points[0],
getMid(points[0], points[1]),
getMid(points[0], points[2])],
degree-1, myTurtle)
sierpinski([points[1],
getMid(points[0], points[1]),
getMid(points[1], points[2])],
degree-1, myTurtle)
sierpinski([points[2],
getMid(points[2], points[1]),
getMid(points[0], points[2])],
degree-1, myTurtle)
def main():
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
myPoints = [[-100,-50],[0,100],[100,-50]]
sierpinski(myPoints,3,myTurtle)
myWin.exitonclick()
main()
try:
turtle.bye()
except:
print("bye")