master
/ 2.6.4 布尔运算.ipynb

2.6.4 布尔运算.ipynb @master

341084b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d487d71
341084b
 
 
 
 
 
 
d487d71
341084b
 
 
 
 
 
 
 
 
 
 
d487d71
341084b
d487d71
 
 
 
 
 
 
 
 
 
 
341084b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d487d71
341084b
d487d71
 
 
 
 
 
 
 
 
 
 
341084b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d487d71
341084b
d487d71
 
 
 
 
 
 
 
 
 
 
341084b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d487d71
 
341084b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 布尔运算"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python 语言支持布尔运算符,<font color=Red>__布尔运算__</font>也称为<font color=Red>__逻辑运算__</font>,包括:  \n",
    "and  (与)  \n",
    "or  (或)   \n",
    "not  (非)   \n",
    "在执行布尔运算或当表达式被用于流程控制语句时,以下值会被解析为False:  \n",
    "False、None、所有类型的数字零、以及空字符串和空容器(包括字符串、元组、列表、字典、集合与冻结集合)。  \n",
    "所有其他值都会被解析为True。  \n",
    "三种运算的表达式与功能描述见表 3.3,按优先级升序排序。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| 运算符 | 表达式    | 功能描述 |\n",
    "| :------ | :--------- | :------------ |\n",
    "| or     | x or   y  | 首先对表达式 x 求值,如果值为True则返回 x的值,否则对表达式y求值并返回其结果值。 |\n",
    "| and    | x   and y | 首先对表达式 x 求值,如果值为False则返回 x的值,否则对表达式y求值并返回其结果值。 |\n",
    "| not    | not   x   | 表达式 x 值为  False时返回 True,否则返回 False。 |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注释:\n",
    "\n",
    "<font size=\"4\">or与and都是<font color=Red>__短路运算符__</font>,因此只有在第一个参数为假值时才会对第二个参数求值。</font>  \n",
    "not 的优先级比非布尔运算符低,因此 not a == b 会被解读为 not (a == b) 而 a == not b 会引发语法错误。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font size=\"4\">and 和 or 两边的 x 和 y 可以是数字、变量或表达式,布尔运算返回的并不是 False 和 True,而是返回参与布尔运算的操作数或表达式的值。</font>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运算符为or时,解释器首先对 or 左边的表达式进行运算,当其值为 True 时直接返回左侧表达式的运算结果。此时不会对右侧表达式进行运算,这种特性也称为短路特性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "hello\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "print(10 or 'hello')  # 先对左侧求值,值为True则返回左侧的值,返回整数 10\n",
    "print('hello' or 10)  # 先对左侧求值,值为True则返回左侧的值,返回'hello'\n",
    "print(10 or '')       # 先对左侧求值,值为True则返回左侧的值,返回整数 10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运算符为or时,解释器仅当 or 左边的表达式运算结果为False时才对右侧的表达式进行运算,此时右侧表达式的值为逻辑运算表达式的值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(0 or 'hello')   # 先对左侧求值,值为False则返回右侧的值,返回'hello'\n",
    "print(0 or False)     # 先对左侧求值,值为False则返回右侧的值,返回False\n",
    "print('' or [])       # 先对左侧求值,值为False则返回右侧的值,返回[]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运算符为and时,解释器首先对 and 左边的表达式进行运算,当左侧表达式的值为 False 时,直接返回左侧表达式的值,而右侧的表达式不会被运算。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(0 and 'hello')   # 先对左侧求值,值为False则返回左侧的值,返回0\n",
    "print(0 and False)     # 先对左侧求值,值为False则返回左侧的值,返回0\n",
    "print('' and [])       # 先对左侧求值,值为False则返回左侧的值,返回''"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运算符为and时,当左侧的表达式值为 True 时才对右侧的表达式进行运算并返回右侧表达式的值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "10\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(10 and 'hello')  # 先对左侧求值,值为True则返回右侧的值,返回'hello'\n",
    "print('hello' and 10)  # 先对左侧求值,值为True则返回右侧的值,返回整数 10\n",
    "print(10 and '')       # 先对左侧求值,值为True则返回右侧的值,返回''"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "逻辑运算 or 和 and 的值是参与运算的表达式的值之一\n",
    "not 运算结果一定是布尔值,值为True或False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(not 10)       # 10是非0整数,布尔值为True,取非结果为False\n",
    "print(not '')       # '',空字符串,布尔值为False,取非结果为True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "布尔运算可放到 <font color=Red>__if__</font>或<font color=Red>__while__</font>  后面的<font color=Red>__条件表达式__</font>中,先得到布尔运算的值,再对返回值做逻辑值检测,根据真值测试的结果决定是否执行分支下的语句。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "if 10 or ' ':     # 10 and ' '布尔运算的值是10,条件运算结果为True\n",
    "    print(True)   # 当10 and ''布尔运算值是True时,输出True\n",
    "else:             # 否则\n",
    "    print(False)  # 输出 False,执行此分支"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上述分支语句的程序可以用下面一行代码实现:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(bool(10 or ''))  # 先得到10 or ' '的结果为10,再用bool(10)返回True输出"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "布尔运算可放到<font color=Red>__赋值语句__</font>中,将布尔运算的结果赋值给前面的变量。  \n",
    "下述语句中,若input()函数接收到非空输入时,值为True,将接收到的字符串赋值给变量;若直接回车,接收到空字符串,此时布尔运算的值为or右侧的“保密”,将“保密”赋值给左侧的变量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "birthdate = input('请输入出生日期: ') or '保密'\n",
    "print(birthdate)                    # 无输入,直接回车时,输出'保密'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "解释器先对布尔运算符左侧的操作数进行运算这种特性称为<font color=Red>__短路特性__</font>。  \n",
    "当<font color=Red>__布尔运算符左侧__</font>的表达式已经可以<font color=Red>__决定布尔运算的结果__</font>时,该语句<font color=Red>__之后__</font>的所有代码都<font color=Red>__不会被执行__</font>。  \n",
    "短路特性可以有效的<font color=Red>__提高效率__</font>。  \n",
    "把容易判断、<font color=Red>__计算量较小的表达式__</font>放在布尔运算符的<font color=Red>__左侧__</font>,可以减少不必要的运算,提高算法效率。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 实例2.3 输入用户信息"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "编程接收用户输入的出生日期,当用户不想公开自己的出生日期时,可以直接输入回车,此时记录“保密”。\n",
    "实现这个功能,可以先接收用户的输入,再用一个分支语句根据用户不同的输入给出不同的输出信息。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "birthdate = input('请输入出生日期: ')  # 接收用户输入的出生日期或回车符\n",
    "if birthdate:          # 当birthdate不为空字符串时,逻辑值检测结果为True\n",
    "    print('你的生日是:', birthdate)   # 有输入时,输出用户输入的出生日期\n",
    "else:                  # 无输入时(直接回车时),输出'保密'\n",
    "    print('你的生日是:', '保密')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "利用布尔运算,这个代码可以用以下方法实现,5行代码精简为2行,且代码的逻辑变得更加简洁:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "birthdate = input('请输入出生日期: ') or '保密'  # 布尔表达式的短路求值结果赋值给birthdate\n",
    "print('你的生日是:', birthdate)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "input()函数的返回值为接收到用户输入的字符串,在上面的代码段中,当用户输入非空时,input() 函数返回值的布尔值为“True”,那么他的值就会赋给 birthdate,且不再对or右侧进行处理;当用户不输入任何字符直接回车时,input()函数获得的是空字符串,其布尔值为False,此时布尔运算的值为or 右侧的字符串'保密',即将字符串“保密”赋值给变量 birthdate。这种表达方法与使用 if 语句效果相同,但更简洁。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "解释器先对逻辑运算符左侧的操作数进行运算这种特性称为短路特性。当发生短路之后,该语句短路处之后的所有代码都不会被执行。短路特性可以有效的提高效率。把容易判断、计算量较小的表达式放在逻辑运算符的左侧,可以减少不必要的运算,提高算法效率。\n",
    "例如判断一个数是否是回文素数时,将判断回文表达式str(i) == str(i)[::-1]放在运算符左侧,当判断不是回文时,不再执行右侧判定素数函数prime(i)。因判定素数的计算量较大,这样设计可以极大的降低运算量,提高效率。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 实例:输出20000以内的所有回文素数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "判断一个数是否是回文素数时,将判断回文表达式`str(i) == str(i)[::-1]`放在运算符左侧,当判断不是回文时,不再执行右侧判定素数函数`prime(i)`。  \n",
    "因为判定素数的计算量较大,这样设计可以极大的降低运算量,提高效率。   \n",
    "断回文素数的完整程序如下(后续章节将详细讲解,这里不讲函数,只让大家了解<font color=Red>__计算量大的__</font>放到<font color=Red>__逻辑运算符右侧__</font>会极大提高效率)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime # 导入datetime,用于计算程序运行时间\n",
    "\n",
    "\n",
    "def prime(n):\n",
    "    \"\"\"接收正整数n,判断是否为素数,返回布尔值\"\"\"\n",
    "    if n < 2:\n",
    "        return False       # 0和1不是素数\n",
    "    for i in range(2, n):  # 遍历(2, n-1)中的数\n",
    "        if n % i == 0:     # 若在(2, n-1)中存在因子则不是素数\n",
    "            return False   # 不是素数时返回False\n",
    "    else:   # for语句遍历(2, n-1)中所有数,未发现因子存在时,才是素数\n",
    "        return True        # 素数时返回True\n",
    "\n",
    "    \n",
    "start = datetime.datetime.now()  # 记录程序开始时间\n",
    "\n",
    "for i in range(20000):\n",
    "    # 利用短路提高效率\n",
    "    if prime(i) and str(i) == str(i)[::-1]: # 先判断素数,再判断回文,效率低\n",
    "        print(i,end=' ')\n",
    "        \n",
    "end = datetime.datetime.now()  # 记录程序结束时间\n",
    "during = (end - start).seconds * 1000 + (end - start).microseconds / 1000  # 计算耗时,精确到毫秒 \n",
    "print(f'\\n耗时:{during}毫秒')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime # 导入datetime,用于计算程序运行时间\n",
    "\n",
    "\n",
    "def prime(n):\n",
    "    \"\"\"接收正整数n,判断是否为素数,返回布尔值\"\"\"\n",
    "    if n < 2:\n",
    "        return False       # 0和1不是素数\n",
    "    for i in range(2, n):  # 遍历(2, n-1)中的数\n",
    "        if n % i == 0:     # 若在(2, n-1)中存在因子则不是素数\n",
    "            return False   # 不是素数时返回False\n",
    "    else:   # for语句遍历(2, n-1)中所有数,未发现因子存在时,才是素数\n",
    "        return True        # 素数时返回True\n",
    "\n",
    "    \n",
    "start = datetime.datetime.now()  # 记录程序开始时间\n",
    "\n",
    "for i in range(20000):\n",
    "    # 利用短路提高效率\n",
    "    if str(i) == str(i)[::-1] and prime(i): # 先判断回文,再判断素数,效率高\n",
    "        print(i,end=' ')\n",
    "        \n",
    "end = datetime.datetime.now()  # 记录程序结束时间\n",
    "during = (end - start).seconds * 1000 + (end - start).microseconds / 1000   # 计算耗时,精确到毫秒 \n",
    "print(f'\\n耗时:{during}毫秒')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "若将回文判定改写为通过取余和整除操作来反转整数再比较的方法,性能还可以进一步提升,表明纯粹的数值运算的优能是优于转字符串再处理的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime # 导入datetime,用于计算程序运行时间\n",
    "\n",
    "\n",
    "def prime(n):\n",
    "    \"\"\"接收正整数n,判断是否为素数,返回布尔值\"\"\"\n",
    "    if n < 2:\n",
    "        return False       # 0和1不是素数\n",
    "    for i in range(2, n):  # 遍历(2, n-1)中的数\n",
    "        if n % i == 0:     # 若在(2, n-1)中存在因子则不是素数\n",
    "            return False   # 不是素数时返回False\n",
    "    else:   # for语句遍历(2, n-1)中所有数,未发现因子存在时,才是素数\n",
    "        return True        # 素数时返回True\n",
    "\n",
    "\n",
    "def reverse_number(num):\n",
    "    \"\"\"接收正整数n,判断是否为回文数,返回布尔值\"\"\"\n",
    "    temp = num\n",
    "    reverse_n = 0\n",
    "    while temp > 0:\n",
    "        reverse_n = reverse_n * 10 + temp % 10\n",
    "        temp //= 10\n",
    "    return num == reverse_n\n",
    "\n",
    "\n",
    "start = datetime.datetime.now()  # 记录程序开始时间\n",
    "\n",
    "for i in range(20000):\n",
    "    # 利用短路提高效率\n",
    "    if reverse_number(i) and prime(i): # 先判断回文,再判断素数,效率高\n",
    "        print(i,end=' ')\n",
    "        \n",
    "end = datetime.datetime.now()  # 记录程序结束时间\n",
    "during = (end - start).seconds * 1000 + (end - start).microseconds / 1000   # 计算耗时,精确到毫秒 \n",
    "print(f'\\n耗时:{during}毫秒')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font face='楷体' color='red' size=5> 练一练 </font>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 补充完成下面的程序,判断输入的年份是否为闰年。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用户输入一个年份,若该年份为闰年,则输出'XXXX年是闰年';否则输出'XXXX年不是闰年'。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "公历闰年判定遵循的规律为:“四年一闰,百年不闰,四百年再闰。”,符合以下条件之一的年份即为闰年\n",
    "1. 能被4整除而不能被100整除。\n",
    "2. 能被400整除。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输入一个正整数表示的年份,判定是否是闰年。\n",
    "闰年的判定标准是能被4整除但不能被100整除的年份,或者能被400整除的年份。这个判定可以用布尔运算来实现:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**输入输出样例:**\n",
    "\n",
    "    输入:2000\n",
    "    输出:2000年是闰年\n",
    "\n",
    "    输入:2022\n",
    "    输出:2022年不是闰年"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "year = int(input())  # 输入整数年份\n",
    "# 参考前例,根据条件使用if...else...判断是否为闰年,并输出对应信息\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 参考答案:\n",
    "year = input()  # 输入要检查的年份\n",
    "\n",
    "is_leap_year = year % 4 == 0 and year % 100 != 0 or year % 400 == 0\n",
    "\n",
    "if is_leap_year:\n",
    "    print(year, '年是闰年')\n",
    "else:\n",
    "    print(year, '年不是闰年')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and优先级高,先计算year % 4 == 0 and year % 100 != 0的值,and两侧的比较运算的结果都是布尔值,再参与到and运算得到的结果也只能是布尔值True或False,再参与优先级较低的 or 运算得到最终结果仍是布尔值 True或False,表示是闰年或非闰年。程序中的布尔运算相当于(year % 4 == 0 and year % 100 != 0) or year % 400 == 0。为了避免引起误读,在同一个表达式中同时出现 and 和 or 时,建议用加小括号的方法明确顺序,这样可以更准确的表达逻辑顺序,同时提高程序的可读性和易维护性。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font face='楷体' color='red' size=5> 练一练 </font>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "改变逻辑运算的顺序,参考回文素数的例子,计算运算时间,考察不同运算顺序是否影响效率?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 补充你的代码\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "逻辑运算符 or、and 和 not 中,not 优先级最高,or 最低,按优先级升序排序为 <font color=Red>__or < and < not__</font>。  \n",
    "在同一个表达式中同时出现 and 和 or 时,建议用加小括号的方法明确顺序,这样可以更准确的表达逻辑顺序,同时提高程序的可读性和易维护性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(1 or 0 and 2 )     # 输出 1\n",
    "# 由于 or 优先级最低,最后参与运算,先计算0 and 2的值,整个表达式等价于在0 and 2上加括号\n",
    "print(1 or (0 and 2))    # 输出 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 实例: 登录验证"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用户名为admin和root的用户的密码均为“123456”。用户输入用户名与密码,当输入的用户名为admin或root,且密码为“123456”时,输出“登录成功”;否则输出“登录失败”。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_name = input()\n",
    "password = input()\n",
    "if user_name == 'root' or 'admin' and password == '123456': # 等价于(user_name == 'root') or ('admin' and password == '123456')\n",
    "    print('登录成功')\n",
    "else:\n",
    "    print('登录失败')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的代码中if后面的条件表达式等价于:  \n",
    "\n",
    "`(user_name == 'root') or ('admin' and password == '123456')`  \n",
    "\n",
    "or两边有一边为真时,就可以通过验证。   \n",
    "当用户输入的用户名为root时,左边为True,or运算发生<font color=Red>__短路__</font>,略过右边表达式,所以不论密码输入什么也可登陆成功。  \n",
    "当用户输入任意用户名时,or左边为False,这时表达式结果由右边and运算结果确定。因为and左边是a非空字符串“admin”,为True,那么只要右侧的比较运算结果为True,即只要密码输入正确,无论用户名是什么,都可以登陆成功;    \n",
    "显然与题目要求不符。  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_name = input()\n",
    "password = input()\n",
    "if (user_name == 'root' or 'admin') and password == '123456': \n",
    "    print('登录成功')\n",
    "else:\n",
    "    print('登录失败')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面修改后的代码,表达式`user_name == 'root' or 'admin'`中字符串'admin'的真值测试结果为True,因此该表达式值恒为True,这时or左边的用户名验证会失效。  \n",
    "无论用户输入任何用户名,只要密码输入正确即可登陆成功,显然与题目要求仍然不符。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "正确的代码如下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_name = input()\n",
    "password = input()\n",
    "if (user_name == 'root' or user_name == 'admin') and password == '123456': \n",
    "    print('登录成功')\n",
    "else:\n",
    "    print('登录失败')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_name = input()\n",
    "password = input()\n",
    "if (user_name == 'admin' and password == '123456') or (user_name == 'root' and password == '123456'): \n",
    "    print('登录成功')\n",
    "else:\n",
    "    print('登录失败')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "user_name = input()\n",
    "password = input()\n",
    "if user_name == 'root' or user_name == 'admin':\n",
    "    if password == '123456': \n",
    "        print('登录成功')\n",
    "else:\n",
    "    print('登录失败')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 运算优先级\n",
    "Python支持多种运算符的混合运算,所有运算符的优先级(由高到低排列)的描述如下表所示。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| 序号 | 运算符                    | 描述                                   |\n",
    "| :----: | :-------------------------: | :-------------------------------------- |\n",
    "| 1    | ()、\\[\\]{}             | <font color=Red>__括号表达式,元组、列表、字典、集合__</font>     |\n",
    "| 2    | x\\[i\\],x\\[m:n\\]          | 索引、切片                              |\n",
    "| 3    | \\*\\*                      | <font color=Red>__幂运算__</font>      |\n",
    "| 4    | +x、 -x、~x                   | 正、负,按位非 NOT                                 |\n",
    "| 5    | \\*、 / 、//、%                 | <font color=Red>__乘法、除法与取模__</font> |\n",
    "| 6    | + 、-                     | <font color=Red>__加法与减__</font>法  |\n",
    "| 7    | <<   、>>                 | 移位                                   |\n",
    "| 8    | &                         | 按位与                                 |\n",
    "| 9   | ^                         | 按位异或                               |\n",
    "| 10   | \\|                        | 按位或                                 |\n",
    "|11   | <、<=、>、>=、!=、== isis not、in、not in |  <font color=Red>__比较运算、成员检测和标识号检测__</font>   |\n",
    "| 12   | not x                     | 逻辑非                                 |\n",
    "| 13   | and                       | <font color=Red>__逻辑与运算符__</font> |\n",
    "| 14   | or                        | <font color=Red>__逻辑或运算符__</font> |\n",
    "| 15   | if…else                   | 条件表达式                             |\n",
    "| 16   | lambda                    | lambda表达式                           |\n",
    "| 17   | :=                        | <font color=Red>__赋值表达式、海象运算符__</font>  |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(4 * 2 ** 3)      # 先幂运算,再计算乘法,输出:32\n",
    "print(3 + 4 * -2)      # 2先取反、与4相乘,再做加法,输出:-5\n",
    "print(3 + 4 * 2 / 2)   # 先计算乘除法,除法运算结果为浮点数,输出:7.0\n",
    "print(3 << 2 + 1)      # 加法优先级高,先2+1,3(11)左移3位变成24 (11000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "括号的优先级最高,可以强制表达式按照需要的顺序求值。可以通过加入小括号“()”的方法来提供弱优先级的优先执行。加了括号,无需比较哪个优先级更高,使程序和表达式更加易于阅读和维护。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 实例:判断是否直角三角形\n",
    "\n",
    "输入三个数a,b,c, 判断能否以它们为三个边长构成直角三角形。若能,输出YES,否则输出NO。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = float(input())\n",
    "b = float(input())\n",
    "c = float(input())\n",
    "\n",
    "# 三角形判定条件:边都为正数,任意两边之和大于第三边\n",
    "if a <= 0 or b <= 0 or c <= 0 or (a + b) <= c or (a + c) <= b or (b + c) <= a:\n",
    "    print('No')\n",
    "# 直角三角形条件,两边平方和等于第三边\n",
    "elif a * a + b * b == c * c or a * a + c * c == b * b or c * c + b * b == a * a:\n",
    "    print('Yes')\n",
    "else:\n",
    "    print('No')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的代码中条件都比较长,可通过改进算法简化,代码如下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = float(input())\n",
    "b = float(input())\n",
    "c = float(input())\n",
    "\n",
    "shortest = min(a, b, c)  # 获得最短边长度\n",
    "longest = max(a, b, c)   # 获得最长边长度\n",
    "middle = sum([a, b, c]) - shortest - longest\n",
    "\n",
    "# 若最小边为负值或长边小于等于其他两边之和时,构不成三角形\n",
    "if shortest <= 0 or shortest + middle <= longest:\n",
    "    print('NO')\n",
    "    \n",
    "# 两边短边长度平方和等于第三边长度平方为直角三角形\n",
    "elif shortest ** 2 + middle ** 2 == longest ** 2:\n",
    "    print('YES')\n",
    "    \n",
    "else:\n",
    "    print('NO')\n",
    "    \n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}