内容包括:
if
语句是是一种条件语句,根据条件为 true 还是 false 运行或执行相关代码。下面是一个简单的示例:
if phone_balance < 5:
phone_balance += 10
bank_balance -= 10
我们来详细讲解下每部分。
if
语句以关键字 if
开始,然后是要检查的条件,在此例中是 phone_balance < 5
,接着是英文冒号。条件用布尔表达式指定,结果为 True 或 False。phone_balance
小于 5 时才执行使 phone_balance
递增和使 bank_balance
递减的行。如果不小于 5,这个 if
块中的代码将被跳过。除了 if
条件之外,if
语句经常还会使用另外两个可选条件。例如:
if season == 'spring':
print('plant the garden!')
elif season == 'summer':
print('water the garden!')
elif season == 'fall':
print('harvest the garden!')
elif season == 'winter':
print('stay indoors!')
else:
print('unrecognized season')
if
:if
语句必须始终以 if
条件开始,其中包含第一个要检查的条件。如果该条件为 True,Python 将运行这个 if
块中的缩进代码,然后跳到 if
语句之后的剩余代码。elif
:elif
条件用来检查其他条件(前提是 if
语句中之前的条件结果为 False)。可以从示例中看出,可以使用多个 elif
块处理不同的情形。else
:最后是 else
条件,它必须位于 if
语句的末尾。该条件语句不需要条件。如果 if
语句中所有前面的语句结果都为 False 时,将运行 else
块中的代码一些其他语言使用花括号来表示代码块从哪开始,从哪结束。在 Python 中,我们使用缩进来封装代码块。例如,if
语句使用缩进告诉 Python 哪些代码位于不同条件语句里面,哪些代码位于外面。
在 Python 中,缩进通常是四个空格一组。请严格遵守该惯例,因为更改缩进会完全更改代码的含义。如果你是 Python 程序员团队的成员,则所有人都必须遵守相同的缩进惯例!
#First Example - try changing the value of phone_balance
phone_balance = 10
bank_balance = 50
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
#Second Example - try changing the value of number
number = 145
if number % 2 == 0:
print("Number " + str(number) + " is even.")
else:
print("Number " + str(number) + " is odd.")
#Third Example - try to change the value of age
age = 35
# Here are the age limits for bus fares
free_up_to_age = 4
child_up_to_age = 18
senior_from_age = 65
# These lines determine the bus fare prices
concession_ticket = 1.25
adult_ticket = 2.50
# Here is the logic for bus fare prices
if age <= free_up_to_age:
ticket_price = 0
elif age <= child_up_to_age:
ticket_price = concession_ticket
elif age >= senior_from_age:
ticket_price = concession_ticket
else:
ticket_price = adult_ticket
message = "Somebody who is {} years old will pay ${} to ride the bus.".format(age, ticket_price)
print(message)
python中的逻辑运算符,比较运算符,算数运算,赋值运算符:
你需要熟悉三个逻辑运算符:
逻辑使用情况 | 布尔型 | 运算符 |
---|---|---|
5 < 3 and 5 == 5 | False | and - 检查提供的所有语句是否都为 True |
5 <= 3 or 5 == 5 | True | or - 检查是否至少有一个语句为 True |
not 5 != 3 | False | not - 翻转布尔值 |
算术运算符 | |
+ | 加 |
- | 减 |
* |
乘 |
/ | 除 |
** | 取幂 |
% | 取余 |
// | 向下取整 |
赋值运算符 | |
= | x = 2 |
+= | x += 3 x = x + 3 |
-= | x -= 2 x = x - 2 |
*= | x *= 1.5 x = x * 0.5 + x |
If
语句有时候会使用更加复杂的条件布尔表达式。可能包括多个比较运算符、逻辑运算符,甚至包括算式。例如:
if 18.5 <= weight / height**2 < 25:
print("BMI is considered 'normal'")
if is_raining and is_sunny:
print("Is there a rainbow?")
if (not unsubscribed) and (location == "USA" or location == "CAN"):
print("send email")
对于非常复杂的条件,你可能需要结合使用 and
、or
和 not
。使用括号可以使运算符组合更清晰。
无论是简单还是复杂的条件,if
语句中的条件都必须是结果为 True 或 False 的布尔表达式,该值决定了 if
语句中的缩进代码块是否执行。
如果我们在 if 语句中使用非布尔对象
代替布尔表达式,Python 将检查其真假值
,判断是否执行缩进代码块
。默认情况下,Python 中对象的真假值被视为 True
,除非在文档中被指定为 False。
以下是在 Python 中被视为 False
的大多数内置对象:
None
和 False
0
、0.0
、Decimal(0)
、Fraction(0, 1)
""
、()
、[ ]
、{ }
、set()
、range(0)
请编写一个 if
语句,使竞争者能够根据自己的得分知道获得了哪个奖品,得分存储在整型变量 points
中。
得分 | 奖励 | Prize in English |
---|---|---|
1 - 50 | 木质兔子玩偶 | wooden rabbit |
51 - 150 | 没有奖品 | no prize |
151 - 180 | 极薄薄荷 | wafer-thin mint |
181 - 200 | 企鹅 | penguin |
所有的上下限都包含在内,points
只能是正整数,最大值为 200。
points = 174
if points <=0:
result = " Invalid score."
if points <= 50:
result = "Congratulations! You won a wooden rabbit!"
elif points <= 150:
result = "Oh dear, no prize this time."
elif points <= 180:
result = "Congratulations! You won a wafer-thin mint!"
elif points <= 200:
result = "Congratulations! You won a penguin!"
else:
result = " Invalid score."
print(result)
我们首先设置 prize = None
,如果得分能够获得奖品,则更新 prize
。然后如果有奖品的话,使用 prize
的真假值输出消息,如果没有奖品,则输出另一条消息。
prize = None
if points <= 50:
prize = "a wooden rabbit"
elif 151 <= points <= 180:
prize = "a wafer-thin mint"
elif points >= 181:
prize = "a penguin"
if prize:
result = "Congratulations! You won " + prize + "!"
else:
result = "Oh dear, no prize this time."
print(result)
逻辑运算符 and
、or
和 not
具有特定的含义,与字面英文意思不太一样。确保布尔表达式的结果和你预期的一样。
# Bad example
if weather == "snow" or "rain": #非布尔表达式,跟据真假值判定‘rain’非空为真值,故if判定语句为true
print("Wear boots!")
# example
if weather == "snow" or weather == "rain":
print("Wear boots!")
这段代码在 Python 中是有效的,但不是布尔表达式,虽然读起来像。原因是 or
运算符右侧的表达式 "rain"
不是布尔表达式,它是一个字符串。稍后我们将讨论当你使用非布尔型对象替换布尔表达式时,会发生什么。
== True
或 == False
比较布尔变量这种比较没必要,因为布尔变量本身是布尔表达式。
# Bad example
if is_cold == True:
print("The weather is cold!")
这是一个有效的条件,但是我们可以使用变量本身作为条件,使代码更容易读懂,如下所示。
# Good example
if is_cold:
print("The weather is cold!")
如果你想检查布尔表达式是否为 False,可以使用 not
运算符。
True
或 False
作为条件# Bad example
if True:
print("This indented code will always get run.")
虽然“True”是一个有效的布尔表达式,但不是有用的条件,因为它始终为 True,因此缩进代码将始终运行。同样,if False
也不应使用,该 if
语句之后的语句将从不运行。
# Another bad example
if is_cold or not is_cold:
print("This indented code will always get run.")
同样,使用你知道将始终结果为 True 的条件(例如上述示例)也是毫无用途的。布尔表达式只能为 True 或 False,因此 is_cold
或 not is_cold
将始终为 True,缩进代码将始终运行
Python 有两种类型的循环:for
循环和 while
循环。for
循环用来遍历可迭代对象。
可迭代对象是每次可以返回其中一个元素的对象,包括字符串、列表和元组等序列类型,以及字典和文件等非序列类型。你还可以使用迭代器和生成器定义可迭代对象。
# iterable of cities
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
# for loop that iterates over the cities list
for city in cities:
print(city.title())
for
开始,表示这是一个 for
循环iteration_variable in iterable
,表示正在被遍历的是可迭代的对象,并且用迭代变量表示当前正在被处理的可迭代对象的元素。在此示例中,迭代变量 city
在第一次迭代时将是“new york city”,在第二次迭代时将是“mountain view。for
循环头部始终以英文冒号 :
结束。for
循环头部之后的是在此 for
循环的每次迭代时运行的缩进代码块。在此块中,我们可以使用迭代变量访问当前正在被处理的元素的值。你可以随意命名迭代变量。常见模式是为迭代变量和可迭代对象指定相同的名称,但是分别使用单复数形式(例如 'city' 和 'cities)
在 for 循环的每次迭代时向新列表中添加元素,创建一个列表。
# Creating a new list
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
修改列表需要使用新的函数 range()
,它是一个内置函数,用于创建不可变的数字序列
。它有三个参数,必须都为整数
。
range(start=0, stop, step=1)
:
start
是该序列的第一个数字,stop
是该序列的最后一个数字大1,step
是该序列中每个数字之间的差即步长。如果未指定的话,start
默认为0,step
默认为1。
指定一个参数
,它将用作 'stop'
的值,另外两个参数使用默认值。E.g. list(range(4))
返回 [0, 1, 2, 3]
指定两个参数
,它们将用作 'start' 和 'stop' 的值
,’step’ 将使用默认值。 E.g. list(range(2, 6))
返回 [2, 3, 4, 5]
为三个参数 'start、stop' 和 'step' 均指定一个值
。 E.g. list(range(1, 10, 2))
返回 [1, 3, 5, 7, 9]
注意,在这些示例中,我们将 range 封装在列表中。因为 range 本身的输出是一个 range 对象
。我们可以通过将其转换为列表
或在 for 循环中遍历它
,查看 range 对象中的值集合。
我们可以使用 range
函数为 cities
列表中的每个值生成索引。这样我们便可以使用 cities[index]
访问列表中的元素,以便直接修改 cities
列表中的值。
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for index in range(len(cities)):
cities[index] = cities[index].title()
虽然修改列表是 range
函数的一个用途,但是并非只有这一个用途。你将经常使用 range
和 for
循环重复某个操作一定的次数。
for i in range(3):
print("Hello!")
写一个遍历 names
列表以创建 usernames
列表的 for
循环。要为每个姓名创建用户名,使姓名全小写并用下划线代替空格。对以下列表运行 for
循环:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
# write your for loop here
for name in names:
usernames.append(name.lower().replace(" ","_"))
print(usernames)
写一个使用 range()
遍历 usernames
中的职位以修改该列表的 for 循环。和上一道练习一样,将每个姓名改成全小写形式并用下划线代替空格
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
# write your for loop here
for i in range(len(usernames)) :
usernames[i] = usernames[i].lower().replace(' ','_')
print(usernames)
写一个 for
循环,用于遍历字符串列表 tokens
并数一下有多少个 XML 标记。XML 是一种类似于 HTML 的数据语言。如果某个字符串以左尖括号“<”开始并以右尖括号“>”结束,则是 XML 标记。使用 count
记录这种标记的数量。
tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0
# write your for loop here
for token in tokens :
if token[0] == "<" and token[-1] == '>':
count +=1
print(count)
写一个 for
循环,用于遍历字符串列表并创建单个字符串 html_str
,它是一个 HTML 列表。例如,如果列表是 items = ['first string', 'second string]
,输出 html_str
应该会输出:
<ul>
<li>first string</li>
<li>second string</li>
</ul>
items = ['first string', 'second string']
html_str = "<ul>\n"
for item in items:
html_str += "<li>{}</li>\n".format(item)
html_str += "</ul>"
print(html_str)
While
循环For
循环是一种“有限迭代”,意味着循环主体将运行预定义的次数。这与“无限迭代”循环不同,无限迭代循环是指循环重复未知次数,并在满足某个条件时结束,while
循环正是这种情况。下面是一个 while
循环的示例。
card_deck = [4, 11, 8, 5, 13, 2, 8, 10]
hand = []
# adds the last element of the card_deck list to the hand list
# until the values in hand add up to 17 or more
while sum(hand) <= 17:
hand.append(card_deck.pop())
这个示例包含两个函数。sum
返回列表中的元素之和,pop
是一个列表方法,它会从列表中删除最后一个元素并返回该元素。
While
循环的组成部分while
开始,表示这是一个 while
循环。sum(hand) <= 17
。while
循环头部始终以冒号 :
结束。while
循环的主体。如果 while
循环的条件为 true,该循环的主体将被执行。每次运行循环主体时,条件将被重新评估。这个检查条件然后运行循环的流程将重复,直到该表达式变成 false。循环的缩进主体应该至少修改测试表达式中的一个变量。如果测试表达式的值始终不变,就会变成无限循环!
写一个 while
循环,用于计算比整数 limit
小的最大平方数,并将其存储在变量 nearest_square
中。平方数是整数乘以自己后的积,例如 36 是一个平方数,因为它等于 6*6
limit = 40
num = 0
while (num+1)**2 < limit:
num += 1
nearest_square = num**2
print(nearest_square)
有时候我们需要更精准地控制何时循环应该结束,或者跳过某个迭代。在这些情况下,我们使用关键字 break
和 continue
,这两个关键字可以用于 for
和 while
循环。
break
使循环终止continue
跳过循环的一次迭代manifest = [("bananas", 15), ("mattresses", 24), ("dog kennels", 42), ("machine", 120), ("cheeses", 5)]
# breaks from the loop when weight reaches or exceeds limit
print("METHOD 1")
weight = 0
items = []
for cargo_name, cargo_weight in manifest:
print("current weight: {}".format(weight))
if weight >= 100:
print(" breaking loop now!")
break
else:
print(" adding {} '{}'".format(cargo_name, cargo_weight))
items.append(cargo_name)
weight += cargo_weight
print("\nFinal Weight: {}".format(weight))
print("Final Items: {}".format(items))
# skips an iteration when adding an item would make weight exceed limit
# breaks from the loop if weight reaches exactly the limit
print("\nMETHOD 2")
weight = 99
items = []
for cargo_name, cargo_weight in manifest:
print("current weight: {}".format(weight))
if weight >= 100:
print(" breaking from the loop now!")
break
elif weight + cargo_weight > 100:
print(" skipping {} ({})".format(cargo_name, cargo_weight))
continue
else:
print(" adding {} ({})".format(cargo_name, cargo_weight))
items.append(cargo_name)
weight += cargo_weight
print("\nFinal Weight: {}".format(weight))
print("Final Items: {}".format(items))
用 break
语句写一个循环,用于创建刚好长 140 个字符的字符串 news_ticker
。你应该通过添加 headlines
列表中的新闻标题创建新闻提醒,在每个新闻标题之间插入空格。如果有必要的话,将最后一个新闻标题从中间截断,使 news_ticker
刚好长 140 个字符。
你可以采用以下方式。
headlines = ["Local Bear Eaten by Man",
"Legislature Announces New Laws",
"Peasant Discovers Violence Inherent in System",
"Cat Rescues Fireman Stuck in Tree",
"Brave Knight Runs Away",
"Papperbok Review: Totally Triffic"]
news_ticker = ""
for headline in headlines:
news_ticker += headline + " "
if len(news_ticker) >= 140:
news_ticker = news_ticker[:140]
break
print(news_ticker)
输出:
Local Bear Eaten by Man Legislature Announces New Laws Peasant Discovers Violence Inherent in System Cat Rescues Fireman Stuck in Tree Brave
zip
和 enumerate
是实用的内置函数,可以在处理循环时用到。
#组合列表
#
items = ['ban','matt','dog','mac','che']
weight = [15,24,42,120,5]
print(list(zip(items,weight)))
#
items = ['ban','matt','dog','mac','che']
weights = [15,24,42,120,5]
for caro in zip(items,weights) :
print((caro[0],caro[1]))
#
items = ['ban','matt','dog','mac','che']
weights = [15,24,42,120,5]
for item,weight in zip(items,weights) :
print("{}: {}".format(item,weight))
#拆分列表
manifest = [("bananas", 15), ("mattresses", 24), ("dog kennels", 42), ("machine", 120), ("cheeses", 5)]
items,weights = zip(*manifest)
print(items)
print(weights)
zip
返回一个将多个可迭代对象组合成一个元组序列的迭代器。每个元组都包含所有可迭代对象中该位置的元素。例如,
list(zip(['a', 'b', 'c'], [1, 2, 3]))
将输出 [('a', 1), ('b', 2), ('c', 3)]
.
正如 range()
一样,我们需要将其转换为列表或使用循环进行遍历以查看其中的元素。
你可以如下所示地用 for
循环拆封每个元组。
letters = ['a', 'b', 'c']
nums = [1, 2, 3]
for letter, num in zip(letters, nums):
print("{}: {}".format(letter, num))
除了可以将两个列表组合到一起之外,还可以使用星号拆封列表。
some_list = [('a', 1), ('b', 2), ('c', 3)]
letters, nums = zip(*some_list)
这样可以创建正如之前看到的相同 letters
和 nums
列表。
#使用for循环遍历一个元组列表
items = ['ban','matt','dog','mac','che']
for i , item in zip(range(len(items)),items):
print(i,item)
#使用enumerate返回元组包含的索引与值
items = ['ban','matt','dog','mac','che']
for i,item in enumerate(items):
print(i,item)
enumerate
是一个会返回元组迭代器的内置函数,这些元组包含列表的索引和值。当你需要在循环中获取可迭代对象的每个元素及其索引时,将经常用到该函数。
letters = ['a', 'b', 'c', 'd', 'e']
for i, letter in enumerate(letters):
print(i, letter)
这段代码将输出:
0 a
1 b
2 c
3 d
4 e
使用 zip
写一个 for
循环,该循环会创建一个字符串,指定每个点的标签和坐标,并将其附加到列表 points
。每个字符串的格式应该为 label: x, y, z
。例如,第一个坐标的字符串应该为 F: 23, 677, 4
。
x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]
points = []
for point in zip(labels, x_coord, y_coord, z_coord):
points.append("{}: {}, {}, {}".format(*point))
for point in points:
print(point)
F: 23, 677, 4
J: 53, 233, 16
A: 2, 405, -6
Q: -12, 433, -42
Y: 95, 905, 3
B: 103, 376, -6
W: 14, 432, 23
X: -5, 445, -1
注意,元组在 format
方法中使用 *
进行了拆封。这样可以使代码更整洁!
使用 zip
创建一个字典 cast
,该字典使用 names
作为键,并使用 heights
作为值。
cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"]
cast_heights = [72, 68, 72, 66, 76]
cast = dict(zip(cast_names, cast_heights))
print(cast)
该输出中的元素顺序可能有变化,因为字典是无序的。
{'Lily': 66, 'Barney': 72, 'Marshall': 76, 'Ted': 72, 'Robin': 68}
将 cast
元组拆封成两个 names
和 heights
元组。
cast = (("Barney", 72), ("Robin", 68), ("Ted", 72), ("Lily", 66), ("Marshall", 76))
names, heights = zip(*cast)
print(names)
print(heights)
('Barney', 'Robin', 'Ted', 'Lily', 'Marshall')
(72, 68, 72, 66, 76)
使用 zip
将 data
从 4x3 矩阵转置成 3x4 矩阵。实际上有一个很酷的技巧。如果想不出答案的话,可以查看解决方案。
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))
print(data_transpose)
((0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11))
这是一个很实用的技巧,有必要了解一下!
使用 enumerate
修改列表 cast
,使每个元素都包含姓名,然后是角色的对应身高。例如,cast
的第一个元素应该从 "Barney Stinson"
更改为 "Barney Stinson 72”
。
cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]
for i, character in enumerate(cast):
cast[i] = character + " " + str(heights[i])
print(cast)
['Barney Stinson 72', 'Robin Scherbatsky 68', 'Ted Mosby 72', 'Lily Aldrin 66', 'Marshall Eriksen 76']
在 Python 中,你可以使用列表推导式快速简练地创建列表。下面是之前的一个示例:
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
可以简写为:
capitalized_cities = [city.title() for city in cities]
借助列表推导式,我们可以使用 for
循环用一步创建一个列表。
我们使用方括号 []
创建列表推导式,括号里包含要对可迭代对象中的每个元素进行评估的条件。上述列表推导式对 cities
中的每个元素 city
调用 city.title()
,以为新列表 capitalized_cities
创建每个元素。
你还可以向列表推导式添加条件语句。在可迭代对象之后,你可以使用关键字 if
检查每次迭代中的条件。
squares = [x**2 for x in range(9) if x % 2 == 0]
上述代码将 squares
设为等于列表 [0, 4, 16, 36, 64],因为仅在 x 为偶数时才评估 x 的 2 次幂。如果你想添加 else
,将遇到语法错误。
squares = [x**2 for x in range(9) if x % 2 == 0 else x + 3]
如果你要添加 else
,则需要将条件语句移到列表推导式的开头,直接放在表达式后面,如下所示。
squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)]
使用列表推导式创建新的列表 first_names
,其中仅包含 names
中的名字(小写形式)
names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]
first_names = [name.split()[0].lower() for name in names]
print(first_names)
使用列表推导式创建一个列表 multiples_3
,能够计算出 1 - 20 这 20 个整数中分别乘以 3 之后的结果。
multiples_3 = [x * 3 for x in range(1, 21)]
print(multiples_3)
使用列表推导式创建一个 passed 的姓名列表,其中仅包含得分至少为 65 分的名字
scores = {
"Rick Sanchez": 70,
"Morty Smith": 35,
"Summer Smith": 82,
"Jerry Smith": 23,
"Beth Smith": 98
}
passed = [name for name, score in scores.items() if score >= 65]
print(passed)
该输出中的元素顺序可能有变化,因为字典是无序的。
['Beth Smith', 'Summer Smith', 'Rick Sanchez']
六月份似乎太忙,将近一个月没有写博客,于是挑一个多元统计分析中的方法写一篇 python 操作实现的。主成分分析(Principle Component Analysis, PCA)是数据降维的一个方法:原始的统计数据中有很多变量,可以采用主成分分析方法将原始数据降维为少数几个变量的数据。主成分分析的求解一般采用特征根分解,即求解原始数据协方差矩阵或相关系数矩阵最大特征根对应的特征向量,即为第一主成分,第二主成分为第二大特征根对应的特征向量,其他的主成分可以依次得出。主成分贡献率为对应特征根占所有特征根
汉语字典专业版2020是一款汉语汉字学习查询字典软件,帮助用户通过拼音、部首进行汉字的查询,并且可以了解3万汉字的笔顺动画视频,帮助用户学习的同时,还可以进行书法跟写,让用户掌握汉语的同时,能够写好毛笔字,使用方法简单,查询汉字内容详细,西西下载即可使用哦!汉语字典专业版2020简介:你们好!感谢你们选择使用这款字典查询工具。字典中大部分汉字均配备了准确的发音、拼音、词组、成语、英译、例句、书写动...
在web开发中,树是比较常见的东西。以前用过zTree,也用过EasyUI-Tree,过了好久后发现都忘记怎么用了。这几天重新回顾了EasyUI-tree的使用,在此将相关知识点记录下来。一、EasyUI-Tree的官方介绍(1)基本使用的介绍 使用方式: 数据格式: 更多详细知识见官方文档: ...
STM32F407开发板贪吃蛇程序和串口,LCD,ADC,DAC各种实验源码
本文分为三个部分JS 数字精度丢失的一些典型问题JS 数字精度丢失的原因解决方案(一个对象+一个函数)一、JS数字精度丢失的一些典型问题1. 两个简单的浮点数相加0.1 + 0.2 != 0.3 // true这真不是 Firebug 的问题,可以用alert试试 (哈哈开玩笑)。看看Java的运算结果再看看Python2. 大整数运算16位和17位数竟然相等,没天理啊。又如var x = 900...
Z变换其实在控制领域,无论是拉氏变换还是z变换,它们最开始的目的都是为了简化问题分析。在对被控对象建模过程中会出现高阶微分方程,而要在时域直接求解它们是很难的,因此对于连续系统我们采用拉氏变换讲问题转换到S域,而对离散系统考虑将问题牵引到Z域,在做了这样的处理后,问题逐渐变为了代数问题,我们在这两个域做分析和设计,最后通过各自的反变换即可回到时域。但现在随着计算机的发展,直接在时域进行求解也成为...
mt3dgis 二次开发 第一个球
问题描述 最近FJ为他的奶牛们开设了数学分析课,FJ知道若要学好这门课,必须有一个好的三角函数基本功。所以他准备和奶牛们做一个“Sine之舞”的游戏,寓教于乐,提高奶牛们的计算能力。 不妨设 An=sin(1–sin(2+sin(3–sin(4+…sin(n))…) Sn=(…(A1+n)A2+n-1)A3+…+2)An+1 FJ想让奶牛们计算Sn的值,请你帮助FJ打印出Sn的...
设计模式 Design Parttern ——外观模式Facade
面向对象接口定义与java一样,使用interface表示,示例代码:与java一样,kotlin定义类时要遵循单继承多实现的原则(即只能继承一个父类,可以实现多个接口)kotlin中定义的类和方法默认都是final的,不可重写,如果要实现重写,需将对应方法类声明为open示例代码:package com.zhusp.kotlinuseopen class Person{ //可...
1、我们要做的第一件事,就是杀掉所有的语言专家。——The first thing we do, lets kill all the language lawyers.这句话的意思,按照柯老师的理解,大概是说不要被语言的细节所左右,对编程语言应该有一个宏观的认识。所以,要先“杀掉”所有的语言专家。2、程序设计范型——过程式程序设计,模块程序设计,面向对象的程序设计,通用型程序设计。 “面