forked from tearf001/Training-Python-Public
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-exec-public.py
More file actions
3194 lines (2554 loc) · 80.6 KB
/
python-exec-public.py
File metadata and controls
3194 lines (2554 loc) · 80.6 KB
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Python训练题:
目录:
0101 HelloWorld
0201 Number
0202 String
0203 Tuple/List
0204 Set/Dict
0205 CLI
0206 File
0301 If-Else/While/For
0302 Function
0401 Module/Package
0402 Class
0501 Exception
0502 Regex
0503 Decorator
0504 Generator
0601 Dir&File
0602 Internet Client
0603 Parallel
0701 Scrapy
0801 GUI-TK
0901 Distribution-Env
1001 UnitTest
1002 DB
1003 WSGI/Flask
1004 Django
1101 Automation
1102 DevOps
1201 DataAnalysis
1202 MachineLearning
1301 BlockChain
1401 OpenStack
1501 MineCraft
1601 IoT
1701 Crack-Debug
'''
# -----------------------------------------------
'''
Tip_010101 要求用户输入一个数字,判断这个数字是否大于42。
Run:
Input: 45
> 42
Code:
'''
'''
Check if input-number > 42
'''
aStr = input("Input: ")
# print(aStr)
aInt = int(aStr)
if aInt > 42:
print("> 42")
else:
print("<= 42")
'''
Tip_010102 要求用户输入两个整数,计算输出两者的和。
Run:
Int A = 32
Int B = 11
32 + 11 = 43
Code:
'''
# -*- coding: utf-8 -*-
aStr = input('Int A = ')
bStr = input('Int B = ')
aInt = int(aStr)
bInt = int(bStr)
print("%s + %s = %s" % (aInt, bInt, aInt+bInt))
'''
Tip_020101. 要求输入一个秒数(整数),输出这些秒相当于多少分钟加多少秒,以及相当于多少分钟(带小数)。
Run:
Please input seconds number: 72
72 sec = 1.200000 min
72 sec = 1 min + 12 sec
Code:
'''
secStr = input("Please input seconds number: ")
sec = int(secStr)
minFloat = float(sec) / 60
minInt, secMod = divmod(sec, 60)
secMod = sec % 60
print("%d sec = %f min" % (sec, minFloat))
print("%d sec = %d min + %d sec" % (sec, minInt, secMod))
'''
Tip_020102. 要求输入一个实数,输出它的平方和开方数,后者保留两位小数。
Run:
Please input float A: 2
2.000000 ** 2 = 4.000000
2.000000 ** 1/2 = 1.414214
2.000000 ** 1/2 = 1.410000
2 ** 1/2 = 1.41
Code:
'''
aFloatStr = input("Please input float A: ")
aFloat = float(aFloatStr)
print("%f ** 2 = %f" % (aFloat, aFloat ** 2))
print("%f ** 1/2 = %f" % (aFloat, aFloat ** 0.5))
print("%f ** 1/2 = %f" % (aFloat, round(aFloat ** 0.5, 2)))
print("%s ** 1/2 = %.2f" % (aFloatStr, pow(aFloat, 0.5)))
'''
Tip_020103 随机生成两个10以内的实数(小数点后两位)并输出到屏幕,要求输入他们的和,输出True/False。
Run:
Please input sum for 4.96 + 4.91 =
9.87
Right!
Code:
'''
from random import random
MIN_DELTA = 10 ** -10
aFloat = round(random() * 10, 2)
bFloat = round(random() * 10, 2)
sumStr = input("Please input sum for %.2f + %.2f =\n" % (aFloat, bFloat))
if abs(float(sumStr) - (aFloat+bFloat)) < MIN_DELTA:
print("Right!")
else:
print("Wrong!")
'''
Tip_020104. 随机生成4个[1-10]之间的自然数并输出到屏幕,要求输入24点的算法,输出True/False。
Run:
Numbers are: 6, 1, 2, 6:
6*1*(6-2)
Right!
Code:
'''
from random import choice, randint
aInt = choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
bInt = choice(range(1, 11))
cInt = randint(1, 10)
dInt = choice(range(1, 11))
aStr = input("Numbers are: %d, %d, %d, %d: \n" % (aInt, bInt, cInt, dInt))
if eval(aStr) == 24:
print("Right!")
else:
print("Wrong!")
'''
Tip_020105. 提示用户输入一个整数(X元人民币),输出这笔钱等于多少张50元,10元,5元,1元纸币(优先用大额纸币)。
Run:
Please input X Yuan:
72
72 Yuan = 1 Fifty, 2 Ten, 0 Five, 2 One
Code:
'''
aNumStr = input("Please input X Yuan:\n")
aNum = int(aNumStr)
tmpNum = aNum
FiftyNum, tmpNum = divmod(tmpNum, 50)
TenNum = tmpNum / 10
tmpNum = tmpNum % 10
FiveNum, OneNum = divmod(tmpNum, 5)
print("%d Yuan = %d Fifty, %d Ten, %d Five, %d One" % (aNum, FiftyNum, TenNum, FiveNum, OneNum))
'''
Tip_020106. 一英寸=2.54厘米。提示用户输入一个英寸数(浮点数),将其换算成浮点数输出,计算时保留两位小数,输出时保留到小数点后四位。
Run:
Please input Inch:
2.698
2.698000 inch = 6.8500 celi
Code:
'''
INCH_CELI = 2.54
aNumStr = input("Please input Inch:\n")
inchNum = float(aNumStr)
celiNum = round(inchNum * INCH_CELI, 2)
print("%f inch = %.4f celi" % (inchNum, celiNum))
'''
Tip_020107. 玛雅人用二十进制计数,如果有个玛雅人跟你说“30”年后是世界末日,请问多少年后是世界末日?
Code:
'''
print(int("30", 20))
'''
Tip_020108. 一些非洲的土著人只会用八进制计数,如果你想给他20瓶可乐换他9只羊,你该怎么告诉他?
Code:
'''
print("%o Coco Cola <=> %o Sheep" % (20, 9))
'''
Tip_020201. 提示用户输入一个字符串,判断该字符串是否包含"apple"子字符串(忽略大小写,Apple, APPLE都算)。
Run:
Please input a string:
I like aPple
'Apple' in 'I like aPple'
Code:
'''
aStr = input("Please input a string:\n")
aStrUpper = aStr.upper()
if "APPLE" in aStrUpper:
print("'Apple' in '%s'" % aStr)
else:
print("'Apple' not in '%s'" % aStr)
'''
Tip_020202. 提示用户输入一个若干个单词,单词要用空白符隔开(两个单词之间可以有多个空白符),程序要将每个单词首字母大写,再用单个空白符连接所有的单词,并输出到屏幕。
Run:
Please input a string:
I like apple
I Like Apple
Code:
'''
aStr = input("Please input a string:\n")
aStrTitle = aStr.title()
aList = aStrTitle.split()
aStrNew = " ".join(aList)
print(aStrNew)
'''
Tip_020203. 提示用户输入一个字符串,判断该字符串是否回文(回文是指正读反读都一样,注意忽略用户输入的字符串两头的空白),并统计字符串长度。
Run:
Please input a string:
bob
len = 3
'bob' is a huiwen string
Code:
'''
aStr = input("Please input a string:\n")
aStr = aStr.strip()
print("len = %d" % len(aStr))
if aStr == aStr[::-1]:
print("'%s' is a huiwen string" % aStr)
else:
print("'%s' is not a huiwen string" % aStr)
'''
Tip_020204. 提示用户输入一个字符串,将其中所有的hello替换成HELLO,并将其中第一个world替换成WORLD。
Run:
Please input a string:
hello world hello world hello world
HELLO WORLD HELLO world HELLO world
Code:
'''
aStr = input("Please input a string:\n")
aStr = aStr.replace("hello", "HELLO")
aStr = aStr.replace("world", "WORLD", 1)
print(aStr)
'''
Tip_020205. 提示用户输入一个字符串,去掉两头空格,逆序间隔1位输出。
Run:
Please input a string:
123456789
97531
Code:
'''
aStr = input("Please input a string:\n")
aStr = aStr.strip()
print(aStr[::-2])
'''
Tip_020206. 提示用户输入一个字符串,统计其中字母a的个数(不区分大小写,A也算),并输出第一个a在字符串中的位置。
Run:
Please input a string:
haha
String 'haha' has 2 a(or A), first a(or A) in 1.
Code:
'''
aStr = input("Please input a string:\n")
aCount = aStr.lower().count('a')
aIndex = aStr.lower().find('a')
print("String '%s' has %d a(or A), first a(or A) in %d." % (aStr, aCount, aIndex))
'''
Tip_020301. 输入若干(>3)个评分,去掉一个最高分,一个最低分,求平均分,保留2位小数。
Run:
Please input some integer numbers:
9 7 5 0 100
The average is: 7.00.
Code:
'''
aStr = input("Please input some integer numbers:\n")
aNumList = [float(item) for item in aStr.split()]
if len(aNumList) < 3:
print("Please input at least 3 integer numbers!")
else:
aNumList.sort()
bNumList = aNumList[1:-1]
avg = sum(bNumList) / len(bNumList)
print("The average is: %0.2f." % avg)
'''
Tip_020302. 输入若干(>1)个整数,生成一个长度为10000的随机数列表,列表中的每个数字都是随机从你输入的几个数字中选取的,统计列表中各个数字出现了多少次。
Run:
Please input some integer numbers:
1 3 7
1 => 3333
3 => 3357
7 => 3310
# 可以看到1,3,7三个数字出现的次数差不多,列表越大,其概率越接近频率。
Please input some integer numbers:
1 1 4
1 => 6617
1 => 6617
4 => 3383
# 可以看到1出现的次数大约是4的两倍,美中不足1的统计出现了两次,尝试把重复的行去掉?
# 后面学习散列(集合,字典)的时候,会用更简单的方法去掉重复的行。
Code:
'''
from random import choice
aStr = input("Please input some integer numbers:\n")
aList = aStr.split()
aNumList = [int(item) for item in aList]
if len(aNumList) < 1:
print("Please input at least 1 integer numbers!")
else:
bNumList = [choice(aNumList) for i in range(10000)]
cNumList = [(i, bNumList.count(i)) for i in aNumList]
for x,y in cNumList:
print("%d => %d" % (x, y))
'''
Tip_020303. 输入5个字符串,去掉字符串两端的空格,按字母顺序逆序输出其中长度大于3的字符串。(按长度排序输出所有字符串,这个在学完函数之后会容易实现)
Run:
Please input string 0: haha
Please input string 1: xi
Please input string 2: hello
Please input string 3: world
Please input string 4: eee
--------------------
world
hello
haha
Code:
'''
aList = []
for i in range(5):
aStr = input("Please input string %d:\t" % i)
aList.append(aStr.strip())
bList = [item for item in aList if len(item) > 3]
bList.sort(reverse=True)
print("-" * 20)
for item in bList:
print(item)
'''
Tip_020304. 输入一个整数,输出比它小的平方数。
Run:
Please input an integer:
19
Numbers: 1 4 9 16
Code:
'''
from math import ceil
aNum = int(input("Please input an integer:\n"))
aList = [str(i**2) for i in range(1, int(ceil(aNum ** 0.5)))]
print("Numbers: %s" % " ".join(aList))
'''
Tip_020305. 输入一个年份,输出其属相,不考虑公历年和农历年之间的差月,比如1983年全年都认为是属猪。
Run:
Please input an integer:
2012
ShengXiao: 2012 => Long
Code:
'''
SX_LIST = "Shu Niu Hu Tu Long She Ma Yang Hou Ji Gou Zhu".split()
aNum = int(input("Please input an integer:\n"))
index = (aNum - 1984) % 12
shengXiao = SX_LIST[index]
print("ShengXiao: %d => %s" % (aNum, shengXiao))
'''
Tip_020306. 输出一个字符串,将其加密(每个字母的ascii加一)输出,再解密输出。
Run:
Please input a string:
I love you
------------------------------
J!mpwf!zpv
I love you
Code:
'''
aStr = input("Please input a string:\n")
print("-" * 30)
aList = [chr(ord(char)+1) for char in aStr]
print("".join(aList))
bList = [chr(ord(char)-1) for char in aList]
print("".join(bList))
'''
Tip_020307. 输入一个整数,输出比它小的能被三整除的自然数。
Run:
Please input a integer:
50
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48
Code:
'''
aInt = int(input("Please input a integer:\n"))
aList = [str(item) for item in range(3, aInt, 3)]
#aList = [str(item) for item in range(1, aInt) if item % 3 == 0]
print(" ".join(aList))
'''
Tip_020401. 让用户输入一行字符串,统计并输出其中每个字符出现的次数。
Run:
Please input a Str:
abcdcdabcd
The stat char list:
a => 2
c => 3
b => 2
d => 3
Code:
'''
aStr = input("Please input a Str:\n")
aDict = {chr:aStr.count(chr) for chr in set(aStr)}
# aDict = {}
# for i in aStr:
# aDict[i] = aDict.get(i, 0) + 1
# # aDict.setdefaut(i, 0)
# # aDict[i] += 1
#
# from collections import Counter
# aDict = Counter(aStr)
print("The stat char list:")
for tmpKey, tmpValue in aDict.items():
print("%s => %d" % (tmpKey, tmpValue))
'''
Tip_020402. 让用户输入A、B两个整数数列,统计并排序输出A数列中独有的整数,B中独有的整数,以及A、B公有的整数。
Run:
Please input int list A: 1 3 5 7 9
Please input int list B: 5 6 7
Only in A: [1, 3, 9]
Only in B: [6]
Both in A & B: [5, 7]
Code:
'''
aNumStr = input("Please input int list A: ")
bNumStr = input("Please input int list B: ")
aNumSet = set([int(item) for item in aNumStr.split()])
bNumSet = set([int(item) for item in bNumStr.split()])
print("Only in A: %s" % sorted(aNumSet - bNumSet))
print("Only in B: %s" % sorted(bNumSet - aNumSet))
print("Both in A & B: %s" % sorted(aNumSet & bNumSet))
'''
Tip_020403. 输入一个句子,按首字母统计句中的单词(限定每个单词都只能由字母组成),输出统计结果。
Run:
Please input a string:
it is my book.
The stat char list:
i => ['it', 'is']
m => ['my']
Code:
'''
aStr = input("Please input a string:\n")
wordList = [word for word in aStr.split() if word.isalpha()]
aDict = {}
for word in wordList:
firstChar = word[0]
aDict.setdefault(firstChar, [])
aDict[firstChar].append(word)
print("The stat char list:")
for tmpKey, tmpValue in aDict.items():
print("%s => %s" % (tmpKey, tmpValue))
'''
Tip_020404. 输入一行字符串,按字母顺序输出其中每个字符出现的位置。
Run:
Please input a string:
abacd
a => [0, 2]
b => [1]
c => [3]
d => [4]
Code:
'''
aStr = input("Please input a string:\n")
aDict = {}
for i, char in enumerate(aStr):
aDict[char] = aDict.get(char, [])
aDict[char].append(i)
for char in sorted(aDict):
print(char, "=>", aDict[char])
'''
Tip_020405 字典格式化有什么好处?
1. 避免顺序问题
2. 避免冗余输入
Tip_020501. 计算命令行参数的和,保留两位小数。
Run: python cmdLineSum.py 4 5 6
The sum was 15.00 !
Code:
'''
import sys
floatList = [float(item) for item in sys.argv[1:]]
print("The sum was %.2f !" % sum(floatList))
'''
Tip_020502. 使用命令行输入职工信息。
1. 职工信息包括姓名,性别,婚姻情况,年龄,薪水,职位。
2. 职工信息中的“职位”字段的缺省值为“staff”。
3. 年龄字段必须是整数,薪水字段必须是浮点数,性别只能是N个选项中的一个,否则报错。
4. 婚姻情况只有两种,已婚和未婚。
Run: python test.py -n John -s male -a 40 -p 50000 -m -r manager
Worker Information:
name => John
sex => male
age => 40
pay => 50000.0
marriageFlag => True
role => manager
Code:
'''
from optparse import OptionParser
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-n", "--name", dest="name", help="name string",
metavar="NAME_STRING")
parser.add_option("-s", "--sex", dest="sex", type="choice",
choices=['male', 'female'], help="sex string",
metavar="SEX_STRING")
parser.add_option("-a", "--age", dest="age", type="int", help="age int",
metavar="AGE_INT")
parser.add_option("-p", "--pay", dest="pay", type="float",
help="pay float", metavar="PAY_FLOAT")
parser.add_option("-m", "--marriage", dest="marriageFlag", action='store_true',
help="marriage flag", metavar="MARRIAGE_FLAG")
parser.add_option("-r", "--role", dest="role", default="staff",
help="role string", metavar="ROLE STRING")
(options, args) = parser.parse_args()
#print(options)
print("Worker Information:")
print("name => ", options.name)
print("sex => ", options.sex)
print("age => ", options.age)
print("pay => ", options.pay)
print("marriageFlag => ", options.marriageFlag)
print("role => ", options.role)
'''
Tip_020601 输出被指定的文件中带有指定字符串的行。
a.txt文件的内容如下:
test 1 apples
apple store
pear banana
Run: python filter.py a.txt apple
test 1 apples
apple store
Code:
'''
import sys
fileName = sys.argv[1]
subStr = sys.argv[2]
for line in open(fileName):
if subStr in line:
print(line, end='')
'''
Tip_020602 统计指定的文件中单词的个数,并追加写到文件末尾。
a.txt文件中内容如下:
test 1 apples
apple store
pear banana
Run: python calNum.py a.txt
Code:
'''
import sys
fileName = sys.argv[1]
wordCount = 0
for line in open(fileName):
wordCount += len(line.split())
open(fileName, 'a').write("\n%d" % wordCount)
'''
Tip_020603 打印指定文件中的内容,在打印时将A字符串替换为B字符串(原文件中的内容则不改变)
a.txt文件中内容如下:
test 1 apples
apple store
pear banana
Run: python replace.py a.txt apple other
test 1 others
other store
pear banana
Code:
'''
import sys
fileName = sys.argv[1]
subStr = sys.argv[2]
repStr = sys.argv[3]
for line in open(fileName):
print(line.replace(subStr, repStr), end='')
'''
Tip_020604 将字典序列化到文件,再从文件读出
略
'''
'''
Tip_030101. 根据用户的输入(直角边长),用*号打印直角等腰三角形
Run:
Please input length:
5
*
**
***
****
*****
Code:
'''
aNum = int(input("Please input length:\n"))
for i in range(1, aNum + 1):
print("*" * i)
'''
Tip_030102. 根据用户的输入(腰长),打印等腰三角形。
Run:
Please input length:
5
*
***
*****
*******
*********
Code:
'''
aNum = int(input("Please input length:\n"))
for i in range(1, aNum + 1):
print(" " * (aNum - i) + "*" * (2*i-1))
'''
Tip_030103. 打印九九乘法表。
Run:
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
……
Code:
'''
import sys
for i in range(1, 10):
for j in range(1, i+1):
k = "%d * %d = %d\t" % (i, j, i*j)
print(k, end='')
# sys.stdout.write(k)
print()
for i in range(1, 10):
aList = []
for j in range(1, i+1):
aList.append("%d * %d = %d" % (i, j, i*j))
print("\t".join(aList))
'''
Tip_030104. 编写猜数字游戏
Run:
please input number:
3
too small
please input number:
67
good ,right
count number times = 2
Code:
'''
from random import randint
GUESS_MAX = 5
c = randint(1, 100)
#print(c)
count = 0
while(count < GUESS_MAX):
a = input("please input number:\n")
a = int(a)
count = count + 1
if a > c:
print("too large")
elif a < c:
print("too small")
else:
print("good ,right")
print("count number times = %d" % count)
break
else:
print("answer = %d" % c)
'''
Tip_030201 实现一个函数sumAny,能满足如下运算:(参数个数是两个或多个,参数彼此之间能做+运算)
print(sumAny(1, 2))
print(sumAny(1.2, 2.3, 3.4))
print(sumAny("hello, ", "world!"))
print(sumAny([0,1,2,3,4], [0,1,2])
输出:
3
6.9
hello, world!
[0, 1, 2, 3, 4, 0, 1, 2]
Code:
'''
from functools import reduce
def sumAny(*arg):
return reduce(lambda x,y:x+y, arg)
print(sumAny(1, 2))
print(sumAny(1.2, 2.3, 3.4))
print(sumAny("hello, ", "world!"))
print(sumAny([0,1,2,3,4], [0,1,2]))
'''
Tip_030202 打印指定文件中最长的一行,如果有多行并列最长,只打印最靠前的最长的一行。
a.txt文件中内容如下:
test 1 apples
apple store
pear banana
Run: python printLong.py a.txt
test 1 apples
Code:
'''
import sys
# from functools import reduce
fileName = sys.argv[1]
# print(reduce(lambda x,y:x if len(x)>len(y) else y, open(fileName)))
print(max(open(fileName), key=len))
'''
Tip_030203 多维列表求和
略
'''
'''
Tip_030204 遍历打印自然数1-30,如果遇到能被2整除的数只打印duck代替,如果遇到能被3整除的数只打印goose代替,如果遇到既能被2又能被3整除的数只打印pig代替。
略
'''
'''
Tip_030205 打印输出符合如下条件之一的100以内的自然数:
1. 能被30整除
2. 个位+十位=10
3. 个位-十位=5
Run:
[0, 5, 16, 19, 27, 28, 30, 37, 38, 46, 49, 55, 60, 64, 73, 82, 90, 91]
Code:
'''
funList = [lambda x: x%30==0,
lambda x: x%10+x/10==10,
lambda x: x%10-x/10==5]
def testFun(i):
return any(fun(i) for fun in funList)
print(filter(testFun, range(100)))
'''
Tip_030206 实现一个函数,将字符串序列按长度排序。
Run:
['bool', 'hello', 'smiles', 'objective']
Code:
'''
testStrList = ["hello", "smiles", "bool", "objective"]
print(sorted(testStrList, key=len))
'''
Tip_030207 打印杨辉三角
Run:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Code:
'''
N = 5
def nextLine(line):
return [1]+map(lambda x,y:x+y, line[:-1], line[1:])+[1]
def printLine(level, index, numList):
strList = [str(i) for i in numList]
print(" "*(level-index) + " ".join(strList))
yhList = [[1], [1,1]]
for i in range(2, N):
yhList.append(nextLine(yhList[i-1]))
for i in range(N):
printLine(N, i, yhList[i])
'''
Tip_030208 汉诺塔问题
略
'''
'''
Tip_030209 写一个选择排序,增加 key 参数
'''
aDict = {'apple': 3.5, 'pear': 5.3, 'orange': 4.2, 'banana': 3.6, 'mango': 6.8}
def mySort(aList, key=lambda x:x):
for i, _ in enumerate(aList):
for x in range(i+1, len(aList)):
if key(aList[i]) < key(aList[x]):
aList[i], aList[x] = aList[x], aList[i]
return aList
print(mySort([1, 5, 3, 6, 2]))
print(mySort(list(aDict.keys()), lambda x:aDict[x]))
'''
Tip_040101 打印输出math模块的所有方法属性和字段属性,打印输出其中fsum函数的用法
Run:
['pow', 'fsum', 'cosh', 'ldexp', 'hypot', 'acosh', 'tan', 'asin', 'isnan', 'log', 'fabs', 'floor', 'atanh', 'modf', 'sqrt', 'frexp', 'degrees', 'lgamma', 'log10', 'asinh', 'fmod', 'atan', 'factorial', 'copysign', 'expm1', 'ceil', 'isinf', 'sinh', 'trunc', 'cos', 'tanh', 'radians', 'sin', 'atan2', 'erf', 'erfc', 'exp', 'acos', 'log1p', 'gamma']
['__package__', '__doc__', '__file__', '__name__', 'pi', 'e']
fsum(iterable)
Return an accurate floating point sum of values in the iterable.
Assumes IEEE-754 floating point arithmetic.
Code:
'''
import math
funList = [attr for attr,value in math.__dict__.items() if callable(value)]
fieldList = [attr for attr,value in math.__dict__.items() if not callable(value)]
print(funList)
print(fieldList)
print(math.fsum.__doc__)
'''
Tip_040102 编写一个模块,使得以下脚本代码运行之后,得到如下输出:
脚本代码:
import aModule
help(aModule)
aModule.aFun()
Run:
Import module: aModule
Help on module aModule:
NAME
aModule - Title example
FILE
/Users/wuwenxiang/Documents/workspace/test/aModule.py
DESCRIPTION
Description example
FUNCTIONS
aFun()
aFun
Code:
'''
'''
Title example
Description example
'''
print("Import module: " + __name__)
def aFun():
print("aFun")
'''
Tip_040103 编写一个包,使得一下脚本代码运行之后,得到输出如下:
脚本代码