NUMBER_OF_ELEMENTS = 5 # For simplicity, use 5 instead of 100
numbers = [] # Create an empty list
sum = 0
for i in range(NUMBER_OF_ELEMENTS):
value = eval(input("Enter a new number: "))
numbers.append(value)
print(numbers)
sum += value
average = sum / NUMBER_OF_ELEMENTS
count = 0 # The number of elements above average
for i in range(NUMBER_OF_ELEMENTS):
if numbers[i] > average:
count += 1
print("Average is", average)
print("Number of elements above the average is", count)
Enter a new number: 5 [5] Enter a new number: 7 [5, 7] Enter a new number: 1 [5, 7, 1] Enter a new number: 9 [5, 7, 1, 9] Enter a new number: 4 [5, 7, 1, 9, 4] Average is 5.2 Number of elements above the average is 2
s = "abdcedf"
l = [2,6,9,5,2,9]
"a" in s
True
6 in l
True
l[-4:-2]
[9, 5]
# Create a list of 99 Boolean elements with value False
isCovered = 99 * [False]
print("isCovered :",isCovered)
endOfInput = False
while not endOfInput:
# Read numbers as a string from the console
s = input("Enter a line of numbers separated by spaces: ")
items = s.split() # Extract items from the string
lst = [eval(x) for x in items] # Convert items to numbers
print("Entered List: ", lst)
for number in lst:
if number == 0:
endOfInput = True
else:
# Mark its corresponding element covered
isCovered[number - 1] = True
print("isCovered List: ", isCovered)
# Check whether all numbers (1 to 99) are covered
allCovered = True; # Assume all covered initially
for i in range(99):
if not isCovered[i]:
allCovered = False # Find one number not covered
break;
# Display result
if allCovered:
print("The tickets cover all numbers")
else:
print("The tickets don't cover all numbers")
isCovered : [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False] Enter a line of numbers separated by spaces: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 0 Entered List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0] isCovered List: [True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True] The tickets cover all numbers
# Create a deck of cards
deck = [x for x in range(0, 52)]
# Create suits and ranks lists
suits = ["Spades", "Hearts", "Diamonds", "Clubs"]
ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "Jack", "Queen", "King"]
# Shuffle the cards
import random
random.shuffle(deck)
# Display the first four cards
for i in range(4):
suit = suits[deck[i] // 13]
rank = ranks[deck[i] % 13]
print("Card number", deck[i], "is", rank, "of", suit)
Card number 41 is 3 of Clubs Card number 43 is 5 of Clubs Card number 10 is Jack of Spades Card number 38 is King of Diamonds
from tkinter import * # Import tkinter
import random
class DeckOfCardsGUI:
def __init__(self):
window = Tk() # Create a window
window.title("Pick Four Cards Randomly") # Set title
self.imageList = [] # Store images for cards
for i in range(1, 53):
self.imageList.append(PhotoImage(file = "image/card/"
+ str(i) + ".gif"))
frame = Frame(window) # Hold four labels for cards
frame.pack()
self.labelList = [] # A list of four labels
for i in range(4):
self.labelList.append(Label(frame,
image = self.imageList[i]))
self.labelList[i].pack(side = LEFT)
Button(window, text = "Shuffle",
command = self.shuffle).pack()
window.mainloop() # Create an event loop
# Choose four random cards
def shuffle(self):
random.shuffle(self.imageList)
for i in range(4):
self.labelList[i]["image"] = self.imageList[i]
DeckOfCardsGUI() # Create GUI
<__main__.DeckOfCardsGUI at 0x1e8b9e97790>
from random import randint # import randint
# Generate a random character between ch1 and ch2
def getRandomCharacter(ch1, ch2):
return chr(randint(ord(ch1), ord(ch2)))
# Generate a random lowercase letter
def getRandomLowerCaseLetter():
return getRandomCharacter('a', 'z')
# Generate a random uppercase letter
def getRandomUpperCaseLetter():
return getRandomCharacter('A', 'Z')
# Generate a random digit character
def getRandomDigitCharacter():
return getRandomCharacter('0', '9')
# Generate a random character
def getRandomASCIICharacter():
return getRandomCharacter(chr(0), chr(127))
#import RandomCharacter # Defined in Listing 6.9
def main():
# Create a list of characters
chars = createList()
# Display the list
print("The lowercase letters are:")
displayList(chars)
# Count the occurrences of each letter
counts = countLetters(chars)
# Display counts
print("The occurrences of each letter are:")
displayCounts(counts)
# Create a list of characters
def createList():
# Create an empty list
chars = []
# Create lowercase letters randomly and add them to the list
for i in range(100):
chars.append(getRandomLowerCaseLetter())
# Return the list
return chars
# Display the list of characters
def displayList(chars):
# Display the characters in the list 20 on each line
for i in range(len(chars)):
if (i + 1) % 20 == 0:
print(chars[i])
else:
print(chars[i], end = ' ')
# Count the occurrences of each letter
def countLetters(chars):
# Create a list of 26 integers with initial value 0
counts = 26 * [0]
# For each lowercase letter in the list, count it
for i in range(len(chars)):
counts[ord(chars[i]) - ord('a')] += 1
return counts
# Display counts
def displayCounts(counts):
for i in range(len(counts)):
if (i + 1) % 10 == 0:
print(counts[i], chr(i + ord('a')))
else:
print(counts[i], chr(i + ord('a')), end = ' ')
main() # Call the main function
The lowercase letters are: t o q t l a z t m e n r m u i s v p i s t k a t e p o s w u k c j q a v f r c t z z g u j p t g z c q e z z h y z e p q s b i c k p d g v f i g b h y y f x c l r e z v s c a r w k o h m h w d v s w l The occurrences of each letter are: 4 a 2 b 6 c 2 d 5 e 3 f 4 g 4 h 4 i 2 j 4 k 3 l 3 m 1 n 3 o 5 p 4 q 4 r 6 s 7 t 3 u 5 v 4 w 1 x 3 y 8 z
l
[2, 6, 9, 5, 2, 9]
# The function for sorting elements in ascending order
def insertionSort(lst):
for i in range(1, len(lst)):
# insert lst[i] into a sorted sublist lst[0..i-1] so that
# lst[0..i] is sorted.
currentElement = lst[i]
k = i - 1
while k >= 0 and lst[k] > currentElement:
lst[k + 1] = lst[k]
k -= 1
# Insert the current element into lst[k + 1]
lst[k + 1] = currentElement
insertionSort(l)
print(l)
[2, 2, 5, 6, 9, 9]
from tkinter import * # Import tkinter
from random import randrange
# Return a random color string in the form #RRGGBB
def getRandomColor():
color = "#"
for j in range(0, 6):
color += toHexChar(randrange(0, 16)) # Add a random digit
return color
# Convert an integer to a single hex digit in a character
def toHexChar(hexValue):
if hexValue <= 9 and hexValue >= 0:
return chr(hexValue + ord('0'))
else: # hexValue <= 15 && hexValue >= 10
return chr(hexValue - 10 + ord('A'))
# Define a Ball class
class Ball:
def __init__(self):
self.x = 0 # Starting center position
self.y = 0
self.dx = 2 # Move right by default
self.dy = 2 # Move down by default
self.radius = 6 # The radius is fixed
self.color = getRandomColor() # Get random color
class BouncingBalls:
def __init__(self):
self.ballList = [] # Create a list for balls
window = Tk() # Create a window
window.title("Bouncing Balls") # Set a title
self.width = 350 # Width of the self.canvas
self.height = 150 # Width of the self.canvas
self.canvas = Canvas(window, bg = "white",
width = self.width, height = self.height)
self.canvas.pack()
frame = Frame(window)
frame.pack()
btStop = Button(frame, text = "Stop", command = self.stop)
btStop.pack(side = LEFT)
btResume = Button(frame, text = "Resume",
command = self.resume)
btResume.pack(side = LEFT)
btAdd = Button(frame, text = "+", command = self.add)
btAdd.pack(side = LEFT)
btRemove = Button(frame, text = "-", command = self.remove)
btRemove.pack(side = LEFT)
self.sleepTime = 500 # Set a sleep time
self.isStopped = False
self.animate()
window.mainloop() # Create an event loop
def stop(self): # Stop animation
self.isStopped = True
def resume(self): # Resume animation
self.isStopped = False
self.animate()
def add(self): # Add a new ball
self.ballList.append(Ball())
def remove(self): # Remove the last ball
self.ballList.pop()
def animate(self): # Move the message
while not self.isStopped:
self.canvas.after(self.sleepTime) # Sleep
self.canvas.update() # Update self.canvas
self.canvas.delete("ball")
for ball in self.ballList:
self.redisplayBall(ball)
def redisplayBall(self, ball):
if ball.x >= self.width:
ball.dx = -2
elif ball.x < 0:
ball.dx = 2
if ball.y >= self.height:
ball.dy = -2
elif ball.y < 0:
ball.dy = 2
ball.x += ball.dx
ball.y += ball.dy
self.canvas.create_oval(ball.x - ball.radius,
ball.y - ball.radius, ball.x + ball.radius,
ball.y + ball.radius, fill = ball.color, tags = "ball")
BouncingBalls() # Create GUI
--------------------------------------------------------------------------- TclError Traceback (most recent call last) Input In [22], in <cell line: 98>() 93 ball.y += ball.dy 94 self.canvas.create_oval(ball.x - ball.radius, 95 ball.y - ball.radius, ball.x + ball.radius, 96 ball.y + ball.radius, fill = ball.color, tags = "ball") ---> 98 BouncingBalls() Input In [22], in BouncingBalls.__init__(self) 53 self.sleepTime = 500 # Set a sleep time 54 self.isStopped = False ---> 55 self.animate() 57 window.mainloop() Input In [22], in BouncingBalls.animate(self) 74 self.canvas.after(self.sleepTime) # Sleep 75 self.canvas.update() # Update self.canvas ---> 76 self.canvas.delete("ball") 78 for ball in self.ballList: 79 self.redisplayBall(ball) File ~\anaconda3\lib\tkinter\__init__.py:2823, in Canvas.delete(self, *args) 2821 def delete(self, *args): 2822 """Delete items identified by all tag or ids contained in ARGS.""" -> 2823 self.tk.call((self._w, 'delete') + args) TclError: invalid command name ".!canvas"