printed
annual_salary
abc
sum_of_data
b4
print("Hello, world!")
语句输出:
"Quotes"
Slashes \//
How '"confounding' "\" it is!
语句输出:
name age height
Archie 17 5'9"
Betty 17 5'6"
Jughead 16 6'
语句输出:
Shaq is 7'1
The string "" is an empty message.
\'""
语句输出:
a b c"
\\
"
'''
C:
in he downward spiral
语句输出:
Dear "DoubleSlash" magazine,
Your publication confuses me. Is it
a \\ slash or a slash?
Sincerely,
Susan "Suzy" Smith
print
语句以生成所需的输出:
print("\"Several slashes are sometimes seen,\"")
print("said Sally. \"I've said so.\" See?")
print("\\ / \\\\ // \\\\\\ ///")
print
语句以生成所需的输出:
print("This is a test of your")
print('knowledge of "quotes" used')
print("in 'string literals.'")
print()
print("You're bound to \"get it right\"")
print("if you read the section on")
print("''quotes.''")
print
语句以生成所需的输出:
print("/ \\ // \\\\ /// \\\\\\")
程序中的错误:
def
)
程序中的错误:
"
def example():
程序输出:
This is message1. This is message2. This is message1. Done with message2. Done with main.
程序输出:
Inside first function Inside third function Inside first function Inside second function Inside first function Inside second function Inside first function Inside third function Inside first function Inside second function Inside first function
程序输出:
Inside first function Inside first function Inside second function Inside first function Inside third function Inside second function Inside first function Inside first function Inside second function Inside first function Inside third function
程序输出:
Inside second function Inside first function Inside first function Inside second function Inside first function Inside third function Inside first function Inside second function Inside first function
程序中的错误:
:
)
"
;
表达式的结果:
8
11
6
4
33
-16
6.4
6
30
1
-1
5.0
2
18
3
4
4
15
8
1
表达式的结果:
9.0
9.6
2.0
6.0
6.0
8.0
1.25
3.0
3.0
3.0
5.0
6.4
37.0
8.5
9.6
4.0
4.8
25.5
grade = 4.0
number % 10
程序中的错误:
,
is"
x
, x
int
and
(number % 100) // 10
(number // 10) % 10
(number % 1000) // 100
(number // 100) % 10
、 和 代码后面的 值:a
b
c
a: 6 b: 9 c: 16
代码的值和代码之后的值:first
second
first: 19 second: 8代码交换变量和 的值。
first
second
重写的代码缩短版本:
first = 8, second = 19 first += second second = first - second first -= second
、 和 代码后面的 值:i
j
k
i: 4 j: 2 k: 1
代码输出:
46 36 23 13
使用变量来避免冗余表达式的程序版本:
def main(): # Calculate my pay at work, based on how many hours I worked each day total_hours = 4 + 5 + 8 + 4 salary = 8.75 pay = total_hours * salary tax_rate = 0.20 taxes_owed = pay * tax_rate print("My total hours worked:") print(total_hours) print("My hourly salary:") print("$" + str(salary)) print("My total pay:") print(pay) print("My taxes owed:") print(taxes_owed) main()
def main(): for i in range(1, 5): print("2 times", i, "=", (2 * i)) main()
2 * count
15 * count - 11
-10 * count + 40
4 * count - 11
-3 * count + 100
for i in range(1, 7): print(18 * i - 22)
功能输出:odd_stuff
4 2 1 0
回路输出:
9 1 7 2 4 3 0 4
回路输出:
+---+ \ / / \ \ / / \ \ / / \ +---+
回路输出:
T-minus 5, 4, 3, 2, 1, Blastoff!
循环输出:
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50
循环输出:
****!****!****! ****!****!****!
2 * line + 2 * SIZE
4 * line + (3 * SIZE)
-line + (2 * SIZE + 3)
输出表:
线 | \ |
! |
/ |
---|---|---|---|
1 | 0 | 22 | 0 |
2 | 2 | 18 | 2 |
3 | 4 | 14 | 4 |
4 | 6 | 10 | 6 |
5 | 8 | 6 | 8 |
6 | 10 | 2 | 10 |
\
/
2 * line - 2
!
-4 * line + 26
Table for output:
line | \ |
! |
/ |
---|---|---|---|
1 | 0 | 14 | 0 |
2 | 2 | 10 | 2 |
3 | 4 | 6 | 4 |
4 | 6 | 2 | 6 |
\
/
2 * line - 2
!
-4 * line + 18
-4 * line + (4 * SIZE + 2)
15 42
10 25
1 3 5
1 3 5 7 9 11 13 15
1 3 5 7 9 11 13 15 17 19 21 23 25
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4
number = 8
whom and who like it
it and him like whom
whom and him like him
stu and boo like who
her and him like who
touch your eye to your head
touch your head to your eye
touch your shoulders to your elbow
touch your eyes and ears to your eyes and ears
touch your toes to your Toes
touch your shoulders to your knees toes
say coke not pepsi or pop
say soda not soda or pepsi
say pepsi not koolaid or pop
say say not pepsi or pepsi
def print_strings(s, n):
for i in range(1, n + 1):
print(s, end=" ")
print()
Temperature
tempc
tempc
main
Body temp in C is: 0.0
results of expressions: math
1.6
2
36.0
64.0
10.0
116.0
7
5
-5
8.0
11.0
102.0
17.0
20.0
13.0
14.0
Output of the program:
3 0 1 2 4 4 3 5 2 4 8 1 5 9 4
grade = 2.7 math.round(grade) # grade = 2.7 grade = math.round(grade) # grade = 3.0 min = math.min(grade, math.floor(2.9)) # min = 2.0 x = math.pow(2, 4) # x = 16.0 x = math.sqrt(64) # x = 8.0 count = 25 math.sqrt(count) # count = 25 count = math.sqrt(count) # count = 5 a = math.abs(math.min(-1, -3)) # a = 3
def count_quarters(cents): return cents % 100 // 25
def main():
age = int(input("How old are you?"))
print("You have", (65 - age), "years until retirement.")
main()
number = int(input("Type an integer: "))
print(number, "times 2 =", (number * 2))
phrase = input("What is your phrase? ")
times = int(input("How many times should I repeat it? "))
for i in range(1, times + 1):
print(phrase)
绘制矩形的正确语法:
e.p.draw_rect(10, 20, 50, 30)
代码中的错误:
draw_line
DrawingPanel
p
以下是更正后的代码:
p = DrawingPanel(200, 200) p.draw_line(50, 86, 20, 35)
黑色矩形正在第二次绘制,因此它覆盖了白色的内圈。以下代码修复了此问题:
panel = DrawingPanel(200, 100) p.set_color("black") p.fill_rect(10, 10, 50, 50) p.set_color("white") p.fill_oval(10, 10, 50, 50)
该程序绘制一系列逐渐变小的黑色圆圈,每个圆圈的右边缘和下边缘都触及窗口的右角和下角。它的输出如下所示:
翻译成逻辑测试的英文陈述:
z % 2 == 1
z <= math.sqrt(y)
y > 0
x % 2 != y % 2
y % z == 0
z != 0
abs(y) > abs(z)
(x >= 0) == (z < 0)
y % 10 == y
z >= 0
x % 2 == 0
abs(x - y) < abs(z - y)
关系表达式的结果:
True
False
True
False
True
False
False
True
True
程序中的错误:
=
==
smaller
smaller = minimum(a, b)
=>
>=
if
调用输出:if_else_mystery_1
叫 | 输出 |
---|---|
一个。if_else_mystery_1(3, 20) |
13 21 |
b.if_else_mystery_1(4, 5) |
5 6 |
c.if_else_mystery_1(5, 5) |
6 5 |
d.if_else_mystery_1(6, 10) |
7 11 |
调用输出:if_else_mystery_2
叫 | 输出 |
---|---|
一个。if_else_mystery_2(10, 2) |
10 6 |
b.if_else_mystery_2(3, 8) |
9 9 |
c.if_else_mystery_1(4, 4)2 |
3 4 |
d.if_else_mystery_2(10, 30) |
29 30 |
用于从用户读取整数的代码,然后打印该数字是否为偶数或其他数字:even
odd
number = int(input("Type a number: ")) if number % 2 == 0: print("even") else: print("odd")
代码错误地打印出不可被 3 整除的偶数是奇数。这是因为该语句与嵌套最紧密的语句 () 匹配,而不是与外部语句匹配。以下更改更正了此问题。else
if
number % 3 == 0
if
if number % 2 == 0: if number % 3 == 0: print("Divisible by 6.") else: print("Odd.")
重构代码以减少冗余:
a = 2 if x < 30: x += 1 print("Python is awesome!", x)
重构代码以减少冗余:
times = int(input("Is your money multiplied 1 or 2 times? ")) donation = int(input("And how much are you contributing? ")) sums += times * donation total += donation if times == 1: count1 += 1 elif times == 2: count2 += 1
如果用户可以键入任何数字,则代码可能需要其他语句来递增正确的 count 变量。if
读取红色/绿色/蓝色的代码:
choice = input("What color do you want? ") if choice.lower() == "r": print("You have chosen Red.") elif choice.lower() == "g": print("You have chosen Green.") elif choice.lower() == "b": print("You have chosen Blue.") else: print("Unknown color:", choice)
给定函数的问题在于变量需要在循环外部声明。以下代码修复了此问题:sum_to
sum
for
def sum_to(n): sums = 0 for i in range(1, n + 1): sums += i return sums
显示的函数不会返回正确的答案。它应该使用累积总和来计算因素;当它找到每个因子时,它不应该返回循环内。相反,它应该在循环外部声明一个计数器,该计数器随着每个因子的出现而递增。以下代码修复了此问题:count_factors
def count_factors(n): count = 0 for i in range(1, n + 1): if n % i == 0: count += 1 return count
表达式等于而不是预期,因为舍入误差。6.800000000000001
6.8
表达式等于而不是预期,因为舍入误差。解决方法是测试该值是否接近而不是完全等于它,如以下代码所示:gpa * 3
9.600000000000001
9.6
9.6
gpa = 3.2 diff = abs(gpa * 3 - 9.6) if diff < 0.1: print("You earned enough credits.")
函数的前提条件是三个边长构成一个有效的三角形。即:print_triangle_type
该函数的前提条件是等级参数的值介于 0 和 100 之间。get_grade
当 代码失败时是三个数字中的最小值;例如,当参数的值为 (4, 7, 2) 时,代码应返回 4,但返回 2。该方法可以正确编写为:median_of_3
n3
def median_of_3(n1, n2, n3): if n1 < n2 and n1 < n3: if n2 < n3: return n2 else: return n3 elif n2 < n1 and n2 < n3: if n1 < n3: return n1 else: return n3 else: # n3 < n1 and n3 < n2 if n1 < n2: return n1 else: return n2
或以下较短版本:
def median_of_3(n1, n2, n3):
return max(max(min(n1, n2), min(n2, n3)), min(n1, n3))
当多个数字是奇数时,代码将失败,因为它使用 而不是 。测试不应嵌套,因为它们不是相互排斥的;多个数字可能是奇数。以下代码修复了此问题:elif
if
def print_num_odd(n1, n2, n3): count = 0 if n1 % 2 != 0: count += 1 if n2 % 2 != 0: count += 1 if n3 % 2 != 0: count += 1 print(count, "of the 3 numbers are odd.")
以下不带语句的版本也有效:if
def print_num_odd(n1, n2, n3):
count = n1 % 2 + n2 % 2 + n3 % 2
print(count, "of the 3 numbers are odd.")
程序输出:
efg nopqrs qr
测试字符串是否以大写字母开头的语句:
if "A" <= the_string[0] <= "Z":
...
以下表达式将生成所需的结果:
name = "Marla Singer" space = name.find(" ") last_name = name[(space + 1) :] first_initial = name[0] last_name_first_initial = last_name + ", " + first_initial + "." print(last_name_first_initial)
或者,您可以使用这个较短的版本:
name = "Marla Singer" print(name[(name.find(" ") + 1):] + ", " + name[0] + ".")
用于检查字符串并确定其字母数量来自字母表的后半部分(或以后)的代码:'n'
# assuming that the string is stored in the variable s count = 0 for ch in s.lower(): if ch >= 'n': count += 1 print(count, "letters come after n.")
1 11 21 31 41 51 61 71 81 91
250
250
250
...
2 4 16
bbbbbabbbbb
10
5
2
1
0
0
0
n = 1
while n <= maxs:
print(n)
n += 1
total = 25
number = 1
while number <= (total / 2):
total = total - number
print(total, number)
number += 1
i = 1
while i <= 2:
j = 1
while j <= 3:
k = 1
while k <= 4:
print("*", end="")
k += 1
print("!", end="")
j += 1
print()
i += 1
mystery
叫 | 输出 |
---|---|
一个。mystery(1) |
1 0 |
b.mystery(6) |
4 2 |
c.mystery(19) |
16 4 |
d.mystery(39) |
32 5 |
e.mystery(74) |
64 6 |
调用输出:mystery
叫 | 输出 |
---|---|
一个。mystery(19) |
19 0 |
b.mystery(42) |
21 1 |
c.mystery(48) |
3 4 |
d.mystery(40) |
5 3 |
e.mystery(64) |
1 6 |
import random
num = random.randint(0, 10)
import random
num = random.randint(25) * 2 + 51
print_letters
def print_letters(text):
if len(text) > 0:
print(text[0], end="")
for i in range(1, len(text)):
print("-" + text[i], end="")
print() # to end the line of output
-1
SENTINEL = -1
num = int(input("Type a number (or " + str(SENTINEL) + " to stop): "))
mins = num
maxs = num
while num != SENTINEL:
if num < mins:
mins = num
elif num > maxs:
maxs = num
num = int(input("Type a number (or " + str(SENTINEL) + " to stop): "))
if mins != SENTINEL:
print("Maximum was", maxs)
print("Minimum was", mins)
表达式的结果:boolean
True
True
False
True
True
False
False
True
True
True
True
False
def is_vowel(c):
c = c.lower() # case-insensitive
return c == "a" or c == "e" or c == "i" or c == "o" or c == "u"
艺术 def is_vowel(c):
return "aeiouAEIOU".find(c) >= 0
is_prime
prime
False
prime
Tue
def is_prime(n):
prime = True
for i in range(2, n):
if n % i == 0:
prime = False
return prime
start_end_same
def start_end_same(string):
return string[0] == string[-1]
has_pennies
def has_pennies(cents):
return cents % 5 != 0
调用输出:mystery
叫 | 返回的值 |
---|---|
一个。mystery(3, 3) |
3 |
b.mystery(5, 3) |
1 |
c.mystery(2, 6) |
2 |
d.mystery(12, 18) |
6 |
e.mystery(30, 75) |
15 |
days
if is_leap_year
if days > 366
days = get_total_days_since_1980()
year = 1980
stop = False
while days > 365 and not stop: # subtract out years
if is_leap_year(year):
if days > 366:
days -= 366
year += 1
else: # new code here
stop = True # new code here
else:
days -= 365
year += 1
not b
(x <= y) or (y <= z)
(x != y) and (x > z)
(x % 2 == 0) or not b
(x // 2 != 13) and not b and (z * 3 != 96)
(z >= x) or (z <= y and x < y)
success = False
while not success:
age = input("Type your age: ")
try:
age = int(age)
success = True
except ValueError:
print("Not an integer; try again.")
success = False
while not success:
gpa = input("Type your GPA: ")
try:
gpa = float(gpa)
success = True
except ValueError:
print("Not a float; try again.")
print("age =", age, " GPA = ", gpa)
prompt = "Please enter a number: "
num1 = get_int(prompt)
num2 = get_int(prompt)
num3 = get_int(prompt)
average = (num1 + num2 + num3) / 3.0
print("Average:", average)
点 | y < x |
y == 0 |
count > 0 |
---|---|---|---|
点 A | 有时 | 有时 | 从不 |
总是 | 有时 | 有时 | |
C点 | 总是 | 总是 | 总是 |
点 D | 有时 | 有时 | 有时 |
E点 | 从不 | 有时 | 有时 |
点 | n > b |
a > 1 |
b > a |
---|---|---|---|
点 A | 有时 | 有时 | 有时 |
总是 | 有时 | 有时 | |
C点 | 有时 | 总是 | 总是 |
点 D | 有时 | 总是 | 从不 |
E点 | 从不 | 有时 | 有时 |
点 | next == 0 |
prev == 0 |
next == prev |
---|---|---|---|
点 A | 有时 | 总是 | 有时 |
B点 | 从不 | 有时 | 有时 |
C点 | 从不 | 从不 | 总是 |
点 D | 有时 | 从不 | 有时 |
E点 | 总是 | 有时 | 有时 |
文件是存储在计算机上的信息的命名集合。我们可以通过打开文件,然后使用 or 方法读取文件:read
readlines
with open("input.txt") as file: lines = name.readlines()
with open("input.txt") as file: lines = name.readlines()
返回的呼叫:split
["welcome...to", "the", "matrix."]
返回的呼叫:split
["in", "fourteen-hundred", "92", "columbus", "sailed", "the", "ocean", "blue", ":)"]
"numbers.dat"
或"C:/Users/yana/Documents/programs/numbers.dat"
"data/homework6/input.dat"
或"C:/Users/yana/Documents/programs/data/homework6/input.dat"
"C:/Users/yana/Documents/homework/data.txt"
"names.txt"
或"/home/yana/Documents/hw6/names.txt"
"data/numbers.txt"
或"/home/yana/Documents/hw6/data/numbers.txt"
"/home/yana/download/saved.html"
将生成以下输出:
input: 6.7 This file has input: several input lines. input: input: 10 20 30 40 input: input: test 6 total
如果 和 使用时产生的输出:readlines
split
input: 6.7 input: This input: file input: has input: several input: input input: lines. input: input: 10 input: 20 input: 30 input: 40 input: input: test 14 total
将自身打印为输出的程序:
def main(): with open("input.txt") as file: lines = file.readlines() for line in lines: print(line.strip()) main()
提示用户输入文件名并将该文件的内容作为输出输出到控制台的代码:
def print_entire_file(): file_name = input("Type a file name: ") with open(file_name) as file: lines = file.readlines() for line in lines: print(line.strip())
将文本行作为输入行并生成框内相同文本作为输出的程序:
# precondition: no line in input is longer than width def print_box(lines, width): print_top_bottom(width) for line in lines: spaces = width - len(line.strip()) print("| " + line.strip() + (" " * spaces) + " |") print_top_bottom(width) def print_top_bottom(width): print("+", end="") for i in range(0, width + 2): print("-", end="") print("+")
将以下四行文本打印到名为 的文件中的代码:message.txt
with open("message.txt", "w") as my_file: print("Testing,", file=my_file) print("1, 2, 3.", file=my_file) print("", file=my_file) print("This is my output file.", file=my_file)
反复提示用户输入文件名直到用户键入系统上存在的文件名的代码。
import os.path def get_file_name(): file_name = "" while not os.path.isfile(file_name): file_name = input("Type a file name: ") return file_name
调用 之前使用的代码:get_file_name
print_entire_file
# reprompts until file name is valid def print_entire_file_2(): file_name = get_file_name() with open(file_name) as file: lines = file.readlines() for line in lines: print(line.strip())
numbers[0]
numbers[9]
numbers[len(numbers) - 1]
numbers[-1]
data = [27, 51, 33, -1, 101]
使用循环将 -6 和 38 之间的所有奇数存储到数组中的代码:
odds = [0] * 22 for i in range(len(odds)): odds[i] = i * 2 - 5
执行代码后,列表包含以下元素值:numbers
[0, 4, 11, 0, 44, 0, 0, 2]
执行代码后,列表包含以下元素值:data
[3, 3, 0, 0, 6, 9, 0, -18]
data = [7, -1, 13, 24, 6]
letters[:2]
letters[3:4]
letters[3:]
letters[:3:-1]
letters[1::2]
def maximum(data):
maxs = data[0]
for i in range(1, len(data)):
if data[i] > maxs:
maxs = data[i]
return maxs
def average(a):
mean = 0.0
for i in range(0, len(a)):
mean += a[i]
return mean / len(a)
data[3:3] = ["dark", "and"]
data[1] = "IS"
i = 0
while i < len(data):
if "a" in data[i]:
data.pop(i)
else:
i += 1
列表遍历是对列表的每个元素的顺序处理。可以通过这种方式解决的问题包括打印列表、比较两个列表的相等性以及在列表中搜索给定值。
使用循环打印名为 的列表的每个元素的代码:for
data
for i in range(len(data)):
print("element [", i, "] is", data[i])
执行代码后,数组包含以下元素值:list
[3, 24, 8, -6, 6, 1]
[1, 2, 6, 8]
[10, 30, 40, 20, 60, 50]
[-4, 1, 25, 4, 16, 9, 64, 36, 49]
[20, 10, 20, 30, 30, 20]
[8, 7, 8, 2, 9, 7, 4, 4, 2, 8]
[33, 28, 33, -1, 3, 28, 17, 9, 33, 17, -1, 33]
def all_less(list1, list2):
if len(list1) != len(list2):
return False
for i in range(len(list1)):
if list1[i] >= list2[i]:
return False
return True
执行代码后,列表包含以下元素值:numbers
[20, 30, 40, 50, 60, 70, 80, 90, 100, 100]
执行代码后,列表包含以下元素值:numbers
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
执行函数后,列表包含以下元素值:mystery
a1
[26, 19, 14, 11, 10]
执行函数后,列表包含以下元素值:mystery2
numbers
[7, 3, 1, 0, 25, 4, 18, -1, 5]
函数调用的结果:mystery3
0
9
6
8
2
def average_length(strings): sums = 0 for i in range(len(strings)): sums += len(strings[i]) return sums / len(strings)
def is_palindrome(lis): for i in range(len(lis) // 2): if lis[i] != lis[len(lis) - 1 - i]: return False return True
[s[0].upper() for s in letters]
[s + s for s in letters]
[(s, s[0]) for s in letters]
程序输出:
2 [0, 0, 1, 0] 1 [0, 0, 1, 0] 3 [0, 0, 1, 1] 2 [0, 0, 1, 1]
程序输出:
2 [0, 1] 1 [0, 1] 1 [1, 2] 0 [1, 2]
def swap_pairs(lis):
for i in range(0, len(lis), 2):
swap(lis, i, i + 1)
append
reverse
clear
def nearest_points(points):
min_dist = 0
for i in range(len(points)):
for j in range(i + 1, len(points)):
dist = distance(points[i], points[j])
if min_dist == 0 or dist < min_dist:
min_dist = dist
return min_dist
def distance(p1, p2):
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
return math.sqrt(dx * dx + dy * dy)
执行代码后,列表包含以下元素值:numbers
[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
循环初始化 的第三行以存储数字 1 到 7:data
for i in range(7): data[2][i] = i + 1
构造包含 5 行和 10 列的整数二维列表的代码,该列表由乘法表填充:
table = [] for i in range(5): table.append([0] * 10) for i in range(5): for j in range(10): table[i][j] = i * j
循环将第二列的内容复制到第五列:
for i in range(6): matrix[i][4] = matrix[i][1]
执行函数后,列表包含以下元素值:mystery2d
numbers
[[4, 5, 6, 6], [5, 6, 7, 7], [6, 7, 8, 8]]
jagged = [] value = 1 for i in range(5): jagged.append([0] * (i + 1)) for j in range(i + 1): jagged[i][j] = value value += 1
您可以使用 for-each 循环检查字典的每个元素。您可以使用关键字检查键是否在字典中。in
如果您尝试将键/值对添加到字典中,并且它已经具有具有相同键的对,则旧对将被新对替换。如果它已经有一对具有相同值,但不具有相同的键,则添加新对而不删除旧对。
您可以通过将键传递给函数来按排序顺序循环访问字典的键。sorted
用于声明将人们的姓名与其年龄相关联的字典的代码:
ages = {} ages["Stuart"] = 85 ages["Marty"] = 12 ages["Allison"] = 25
艺术
ages = {"Stuart": 85, "Marty": 12, "Allison": 25}
代码执行后字典中包含的键和值:
{17: 'Steve', 34: 'Louann', 5: 'Moshe', 27: 'Donald', 2350: 'Orlando', 15: 'Moshe'}
代码执行后字典中包含的键和值:
{132: 'OneThreeTwo', 8: 'Ocho', 9828: 'Ninety-eight18', 8650: 'Eighty-sixForty-one', 50: 'Fifty', 79: 'Seventy-nine'}
传递每个字典的方法时生成的输出:mystery
{'one': 'un', 'four': 'quatre', 'deux': 'two', 'cinq': 'five', 'three': 'trois'}
{'computer': 'program', 'car': 'drive', 'board': 'skate'}
{'begin': 'ready', 'boy': 'girl', 'first': 'last', 'ebert': 'siskel', 'H': 'T'}
{'cotton': 'rain', 'light': 'tree', 'tree': 'violin', 'seed': 'tree'}
传递每对字典时传递函数时返回的结果:mystery
{'mumble': 'fire', 'baz': 'wind', 'bar': 'earth', 'foo': 'air'}
{'one': 'dos', 'five': 'quatro', 'three': 'tres'}
{'c': 'seven', 'g': 'seven', 'b': 'years', 'e': 'ago'}
传递每个列表时传递函数时返回的结果:mystery
{1: [1], 2: [1, 1], 3: [], 4: [1], 34: [], 14: []}
{1: [1, 1, 1], 2: [1, 1], 4: [1, 1]}
{43: [1], 44: [], 45: [1, 1], 54: [1]}
传递每个字典的函数时返回的结果:mystery
{3: {'and'}, 4: {'hello', 'world'}}
{1: {'banana', 'kiwi'}, 2: {'peach'}, 3: {'apple', 'nectarine'}}
{'the': {'is', 'has'}, 'and': {'the', 'and'}}
如果要避免重复或希望能够快速搜索集合,则应使用集合而不是列表。
您可以使用 for-each 循环检查集合中的每个元素。
您可以使用关键字检查值是否包含在集中。in
代码执行后,该集包含以下元素(按某种顺序):
{32, 18274, 18212, 9, 12, 29999, 9074}
代码执行后,该集包含以下元素(按某种顺序):
{4, 42, 11, 12, 84, 247, 94}
要执行并集,请使用 创建一个新集,其中包含两个集中的所有项目。要执行交集,请使用 创建一个新集,其中两个集中只有项目。set1 | set2
set1 & set2
要找到所有不饿、年老或贫穷或两者兼而有之的男人:(male - hungry) & (old | poor)
mystery
{'jessica', 'amanda', 'helene'}
{'riley'}
{'charlie', 'phil', 'alex', 'roy', 'tyler'}
递归是一种技术,其中算法以其自身来表示。递归函数与常规函数的不同之处在于,它在其主体中包含对自身的一个或多个调用。
基本情况是递归函数不需要进行递归调用来解决问题的情况。递归情况是递归函数调用自身的情况。递归函数需要这两种情况,因为递归情况被重复调用,直到达到基本情况,从而停止递归调用链。
每次调用时函数生成的输出:mystery1
1
1, 2
1, 3
1, 2, 4
1, 2, 4, 8, 16
1, 3, 7, 15, 30
1, 3, 6, 12, 25, 50, 100
每次调用时函数生成的输出:mystery2
113
140, 70
168, 84, 42
120, 60, 30
160, 80, 40, 20, 10
每次调用时函数生成的输出:mystery_x_y
4
8, 4, 8
16, 8, 16
12, 8, 4, 8, 12
12, 9, 6, 3, 6, 9, 12
函数的递归版本:double_reverse
def double_reverse(s): if len(s) > 0: last = s[-1] print(last, end="") print(last, end="") double_reverse(s[0:-1])
所示函数的版本没有任何基本情况,因此递归调用永远不会停止。可以通过添加不进行递归调用的检查来修复它。pow
y == 0
该函数的第二个版本比第一个版本更有效,因为它需要较少的递归调用。这两个版本都是递归的。pow
函数为每次调用返回的值:mystery4
6
4
7
0
1
方法为每个调用返回的值:mystery5
57
1029
-74
2438
132483
函数的递归版本:factorial
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)
基本情况陈述有一个错误:它应该测试小于10的数字,而不是大于10。以下是正确的行:if
if n < 10:
当递归所需的参数与客户端要传递的参数不匹配时,请使用具有客户端所需签名的函数和具有递归所需签名的帮助器函数。
以下版本的代码提高了效率:fibonacci
def fibonacci(n): if n <= 2: return 1 else: return fibonacci2(n, 3, 1, 1) def fibonacci2(n, i, prev, curr): if n == i: return prev + curr else: return fibonacci2(n, i + 1, curr, prev + curr)
分形是递归构造以包含自身较小版本的图像。递归函数在绘制分形图像时很有用,因为它们可以优雅地表达图像的递归性质。
用于创建和绘制正六边形的代码:
def draw_hexagon(panel, x, y, size): p1 = (x, y + size // 2) p2 = (x + size // 3, y) p3 = (x + 2 * size // 3, y) p4 = (x + size, y + size // 2) p5 = (x + 2 * size // 3, y + size) p5 = (x + size // 3, y + size) panel.fill_polygon(p1, p2, p3, p4, p5)
递归是实现回溯算法的有效方法,因为决策的记忆和要返回的点由递归调用堆栈表示。“选择,探索,取消选择”的模式由每个单独选择的递归调用优雅地表示。
决策树是对递归回溯函数在算法中任何一点可以做出的选择集的描述。
如果回溯解决方案在递归函数中首先而不是最后一个探索了 NE,则(1, 2)的路径的图将得出的决策树:explore
start (0, 0) | +--- NE (1, 1) | | | +--- NE NE (2, 2) | | | +--- NE N (1, 2) - output | | | +--- NE E (2, 1) | +--- N (0, 1) | | | +--- N NE (1, 2) - output | | | +--- N N (0, 2) | | | | | +--- N N NE (1, 3) | | | | | +--- N N N (0, 3) | | | | | +--- N N E (1, 2) - output | | | +--- N E (1, 1) | | | +--- N E NE (2, 2) | | | +--- N E N (1, 2) - output | | | +--- N E E (2, 1) | +--- E (1, 0) | +--- E NE (2, 1) | +--- E N (1, 1) | | | +--- E N NE (2, 2) | | | +--- E N N (1, 2) - output | | | +--- E N E (2, 1) | +--- E E (2, 0)
如果解决方案首先而不是最后探索 NE,则解决方案将按以下顺序打印:
moves: NE N moves: N NE moves: N N E moves: N E N moves: E N N
在整棵树的第二层有 64 个条目。在整棵树的第三层有 512 个条目。
如果我们的 8 Queens 算法尝试了棋盘上每个可能的方块来放置每个女王,那么在整棵树的第 8 层也是最后一级,将有 (64*63*62*61*60*59*58*57) = 178,462,987,637,760 个条目。我们的算法通过在电路板的每一列中只放置一个女王来避免如此大量的选择。
8 Queens 函数在找到问题解决方案后停止。这是因为代码在其递归调用周围具有以下行:explore
if explore(b, col + 1): return True
可以修改代码,以便通过将代码更改为以下内容来查找并输出问题的每个解决方案:
explore(b, col + 1)
并将基本情况更改为以下内容:
if col > len(b): print("One solution is as follows:") b.print() return True
可以使用循环对列表执行顺序搜索,也可以使用 对列表进行排序,然后使用 对列表执行二进制搜索。sort
bisect.bisect_left
最接近二进制搜索算法需要在一百万个整数列表中检查的元素数的值:
e. 小于 1%(10,000 或更少)如果对列表进行排序,则应使用二进制搜索。否则,您将不得不使用顺序搜索。
O(日志 N)
O(N)
O(N2)
O(N2)
给定算法的复杂度类,以 N 为单位:
给定语句的复杂性类:
两个顺序搜索的运行时复杂性均为 O(N)。
二进制搜索需要排序的数据集,因为它使用排序跳转到下一个索引。如果元素无序,则不能保证搜索找到目标元素。
对 60 个元素的二进制搜索最多检查 6 个元素,因为 log2 60(四舍五入时)等于 6。
该算法将检查索引 4、6 和 5,并将返回 -1。该算法无法正常工作,因为输入数组未排序。
二进制搜索算法将检查以下索引,并为每个搜索返回以下值:
在选择排序算法的一次传递(单个交换)之后,列表的状态为:
d.[-4, 17, 3, 94, 46, 8, 29, 12]
选择排序算法的所有步骤:
[29, 17, 3, 94, 46, 8, -4, 12] [-4, 17, 3, 94, 46, 8, 29, 12] [-4, 3, 17, 94, 46, 8, 29, 12] [-4, 3, 8, 94, 46, 17, 29, 12] [-4, 3, 8, 12, 46, 17, 29, 94] [-4, 3, 8, 12, 17, 46, 29, 94] [-4, 3, 8, 12, 17, 29, 46, 94]
[33, 14, 3, 95, 47, 9, -42, 13] [-42, 14, 3, 95, 47, 9, 33, 13] [-42, 3, 14, 95, 47, 9, 33, 13] [-42, 3, 9, 95, 47, 14, 33, 13] [-42, 3, 9, 13, 47, 14, 33, 95] [-42, 3, 9, 13, 14, 47, 33, 95] [-42, 3, 9, 13, 14, 33, 47, 95]
[7, 1, 6, 12, -3, 8, 4, 21, 2, 30, -1, 9] [-3, 1, 6, 12, 7, 8, 4, 21, 2, 30, -1, 9] [-3, -1, 6, 12, 7, 8, 4, 21, 2, 30, 1, 9] [-3, -1, 1, 12, 7, 8, 4, 21, 2, 30, 6, 9] [-3, -1, 1, 2, 7, 8, 4, 21, 12, 30, 6, 9] [-3, -1, 1, 2, 4, 8, 7, 21, 12, 30, 6, 9] [-3, -1, 1, 2, 4, 6, 7, 21, 12, 30, 8, 9] [-3, -1, 1, 2, 4, 6, 7, 21, 12, 30, 8, 9] [-3, -1, 1, 2, 4, 6, 7, 8, 12, 30, 21, 9] [-3, -1, 1, 2, 4, 6, 7, 8, 9, 30, 21, 12] [-3, -1, 1, 2, 4, 6, 7, 8, 9, 12, 21, 30]
[6, 7, 4, 8, 11, 1, 10, 3, 5, 9] [1, 7, 4, 8, 11, 6, 10, 3, 5, 9] [1, 3, 4, 8, 11, 6, 10, 7, 5, 9] [1, 3, 4, 8, 11, 6, 10, 7, 5, 9] [1, 3, 4, 5, 11, 6, 10, 7, 8, 9] [1, 3, 4, 5, 6, 11, 10, 7, 8, 9] [1, 3, 4, 5, 6, 7, 10, 11, 8, 9] [1, 3, 4, 5, 6, 7, 8, 11, 10, 9] [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]
合并 32 个元素将生成总共 63 个调用,并将执行该操作 31 次。merge_sort
merge
元素在选择排序的最外层循环的五次传递后的状态已经发生:
[1, 2, 3, 4, 5, 11, 9, 7, 8, 10]
跟踪合并排序算法:
[7, 2, 8, 4, 1, 11, 9, 5, 3, 10] [7, 2, 8, 4, 1], [11, 9, 5, 3, 10] [7, 2], [8, 4, 1], [11, 9], [5, 3, 10] [7], [2], [8], [4, 1], [11], [9], [5], [3, 10] [4], [1], [3], [10] [8], [1, 4], [5], [3, 10] [2, 7], [1, 4, 8], [9, 11], [3, 5, 10] [1, 2, 4, 7, 8], [3, 5, 9, 10, 11] [1, 2, 3, 4, 5, 7, 8, 9, 10, 11]
元素在选择排序的最外层循环的五次传递后的状态已经发生:
[-3, -1, 1, 2, 4, 8, 7, 21, 12, 30, 6, 9]
跟踪合并排序算法:
[7, 1, 6, 12, -3, 8, 4, 21, 2, 30, -1, 9] [7, 1, 6, 12, -3, 8], [4, 21, 2, 30, -1, 9] [7, 1, 6], [12, -3, 8], [4, 21, 2], [30, -1, 9] [7], [1, 6], [12], [-3, 8], [4], [21, 2], [30], [-1, 9] [1], [6], [-3], [8], [21], [2], [-1], [9] [7], [1, 6], [12], [-3, 8], [4], [2, 21], [30], [-1, 9] [1, 6, 7], [-3, 8, 12], [2, 4, 21], [-1, 9, 30] [-3, 1, 6, 7, 8, 12], [-1, 2, 4, 9, 21, 30] [-3, -1, 1, 2, 4, 6, 7, 8, 9, 12, 21, 30]
以下关于排序和大哦的陈述是正确的:
b.合并排序通过在每个步骤中将列表分成两半,然后递归地排序并将两半合并在一起来实现 O(N log N) 运行时。合并排序算法的痕迹:
[29, 17, 3, 94, 46, 8, -4, 12] [29, 17, 3, 94], [46, 8, -4, 12] [29, 17], [3, 94], [46, 8], [-4, 12] [29], [17], [3], [94], [46], [8], [-4], [12] [17, 29], [3, 94], [8, 46], [-4, 12] [3, 17, 29, 94], [-4, 8, 12, 46] [-4, 3, 8, 12, 17, 29, 46, 94]
[6, 5, 3, 7, 1, 8, 4, 2] [6, 5, 3, 7], [1, 8, 4, 2] [6, 5], [3, 7], [1, 8], [4, 2] [6], [5], [3], [7], [1], [8], [4], [2] [5, 6], [3, 7], [1, 8], [2, 4] [3, 5, 6, 7], [1, 2, 4, 8] [1, 2, 3, 4, 5, 6, 7, 8]
[33, 14, 3, 95, 47, 9, -42, 13] [33, 14, 3, 95], [47, 9, -42, 13] [33, 14], [3, 95], [47, 9], [-42, 13] [33], [14], [3], [95], [47], [9], [-42], [13] [14, 33], [3, 95], [9, 47], [-42, 13] [14, 33], [3, 95], [9, 47], [-42, 13] [3, 14, 33, 95], [-42, 9, 13, 47] [-42, 3, 9, 13, 14, 33, 47, 95]
过程编程将程序视为要执行的一系列操作或命令。面向对象编程将程序视为一组名为对象的交互实体,每个实体都跟踪相关数据和行为。
对象是封装数据和对数据进行操作的行为的实体。类是一类对象的蓝图,用于指定对象将具有的数据和行为以及如何构造它。
程序输出:
14 14 7 9 14 2 18 18 7 9 14 18
对象的状态可能包括刚刚计算的数字,以及当前正在输入的另一个数字。更复杂的对象还可能包括存储附加值的内存功能。对象的行为可能包括加法、减法、乘法、除法以及执行其他数学运算(如幂、对数和三角函数,如正弦和余弦)的方法。Calculator
Calculator
Calculator
属性是存在于对象内部的变量。参数是方法内部的变量,其值是从外部传入的。属性具有不同的语法,因为它们是在类的顶部声明的,而不是在方法的标头中声明的。属性的作用域位于整个类中,而参数的作用域仅限于方法。
Name
表示人名的类:
# A Name object represents a name such as "John Q. Public". # This version contains only data attributes and a constructor. class Name: def __init__(self, first, middle, last): self.first_name = first self.middle_initial = middle self.last_name = last
访问器为客户端提供对对象中某些数据的访问权限,而赋值器允许客户端以某种方式更改对象的状态。访问者的名称通常以“get”或“is”开头,而突变者的名称通常以“set”开头。
在对象上调用方法的正确语法:compute_interest
BankAccount
result = acct.compute_interest(42)
Name
类,有两种方法:
# A Name object represents a name such as "John Q. Public". # This version adds the methods get_normal_order and get_reverse_order. class Name: def __init__(self, first, middle, last): self.first_name = first self.middle_initial = middle self.last_name = last # The name in normal order such as "John Q. Public". def get_normal_order(self): return self.first_name + " " + self.middle_initial + ". " + self.last_name # The name in reverse order such as "Public, John Q.". def get_reverse_order(self): return self.last_name + ", " + self.first_name + " " + self.middle_initial + "."
若要使类的对象可打印,请在其中定义一个方法。__str__
该语句等效于以下内容:print
print(d1.__str__())
__str__
类的方法:Name
# Returns a string representation of this Name, such as "John Q. Public". def __str__(self): return self.first_name + " " + self.middle_initial + ". " + self.last_name艺术
# Returns a string representation of this Name, such as "John Q. Public". def __str__(self): return self.get_normal_order()
抽象是一种在较高层次上关注问题而不必担心次要细节的能力。对象通过为我们提供具有复杂行为的更强大的数据片段来提供抽象,而无需直接管理和操作数据。
若要访问私有属性,请创建返回其值的属性。例如,添加一个属性以访问对象的 data 特性。还可以编写从对象返回数据的访问器方法。name
_name
类的封装版本:Name
# A Name object represents a name such as "John Q. Public". # This version is encapsulated with underscored attributes and properties. class Name: # Initializes a new Name with the given values. def __init__(self, first, middle, last): self._first = first self._middle = middle self._last = last # Returns the person's first name. @property def first_name(self): return self._first # Returns the person's middle initial. @property def middle_initial(self): return self._middle # Returns the person's last name. @property def last_name(self): return self._last # The name in normal order such as "John Q. Public" def get_normal_order(self): return self._first + " " + self._middle + ". " + self._last # The name in reverse order such as "Public, John Q.". def get_reverse_order(self): return self._last + ", " + self._first + " " + self._middle + "." # The name in normal order such as "John Q. Public" def __str__(self): return self.get_normal_order()
类的属性设置器:Name
class Name: ... # Sets the first name to the given value. @first_name.setter def first_name(self, value): self._first = value # Sets the middle initial to the given value. @middle_initial.setter def middle_initial(self, value): self._middle = value # Sets the last name to the given value. @last_name.setter def last_name(self, value): self._last = value
封装允许您更改类的内部实现,而无需将其外部视图更改为客户端。当一个类被封装时,客户端不应该直接访问它的属性,所以只要外部视图(方法行为)是一致的,更改这些字段就不会干扰客户端行为。
凝聚力是一个类的内容如何组合在一起的概念。当一个类的每个属性都存储与对象相关的重要状态并且每个方法以某种方式与该状态交互以产生有用的行为时,可以看出该类是内聚的。
我们没有将控制台 I/O 代码放入我们的类中,因为这样做会强制客户端使用这些确切的 I/O 消息。通过将 I/O 代码保留在 之外,我们使其独立于其客户端。Stock
Stock
类的访问器方法:Stock
# Returns this Stock's symbol value. def get_symbol(self): return self._symbol # Returns this Stock's total number of shares purchased. def get_total_shares(self): return self._total_shares # Returns this Stock's total cost for all shares. def get_total_cost(self): return self._total_cost
由于函数式编程非常关注单个函数,因此经常使用函数式编程的程序员社区得出的结论是,应尽可能避免副作用。没有副作用的函数很容易推理、重用、组合和并行化。
调用被视为副作用,因为它会产生明显的结果,即将输出输出打印到控制台。因此,您可以通过查找输出来检测是否调用了给定函数。这并不意味着打印输出是一件坏事,只是它是一种副作用。print
该函数的副作用是它修改传入的列表。可以通过让它返回新的列表状态而不是更改现有列表来更改它以消除副作用。
# Returns a new list whose values are twice as large as
# the values of all elements in the given list.
def double_all(lis):
result = [0] * len(lis)
for i in range(len(lis)):
result[i] = 2 * lis[i]
return result
lambda num: num * num
lambda a, b: max(a, b)
lambda first, last: last + ", " + first
[10, 28, 33, 28, 49, 56, 49]
list(filter(lambda num: num >= 0, numbers))
绑定变量位于 lambda 内部,通常是其参数之一。自由变量是在 lambda 代码中引用的变量,在 lambda 外部声明并包含在其闭包中。
自由变量为 ,绑定变量为 (第二个) 和 。a
b
c