python练习实例

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
try:
    fh = open("testfile","w")
    fh.write("testing")
except Exception as e:
    print str(e)
else:
    print 'sucessed'
    fh.close()
 
def functionName(level):
    if level <2:
        raise Exception("Invalid level!",level)
 
 
 
if __name__ == "__main__":
    functionName(1)<br>#.............................................
class Networkerror(RuntimeError):
    def __init__(self,arg):
        self.args = arg
try:
    raise Networkerror("Bad hostname")
except Networkerror,e:
    print e.args
#........................................................
while True:
    reply = input('Enter text:')  
    if reply == 'stop':break
    try:
        num = int(reply)
    except:
        print('bad' * 8)
    else:
        print (int(reply) * 2)
    print 'Bye'
#...................................................
import py_compile
import sys
 
file = raw_input("please enter your name")
py_compile.compile(file)
sys.exit()
#................................................
#汉诺塔问题
def my_print(args):
    print args
 
def move(n,a,b,c):
    my_print((a,'-->',c)) if n==1 else (move(n-1,a,c,b) or move(1,a,b,c) or move(n-1,b,a,c))
 
move(3,'a','b','c')
#...............................................................
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
    print '当前水果:', fruits[index]
 
print "Good bye!"<br>
#...............................................
#判断10 ~20的范围内质数和非质数
Prime = []
NoPrime = []
for num in range(10,20):
    for i in range(2,num):
        if num%i == 0:
            print '%d不是质数' % num
            NoPrime.append(num)
            break
    else:
        print '%d是质数' % num
        Prime.append(num)
print '质数为:', Prime
print '非指数为:', NoPrime
 
#使用内置 enumerate 函数进行遍历:
sequence = [12, 34, 34, 23, 45, 76, 89]
for i,j in enumerate(sequence):
    print i,j
#.............................................<br>
#打印空心等边三角形
rows = int(raw_input('输入行数:'))
for i in range(0, rows):
    for k in range(0, 2 * rows - 1):
        if (i != rows - 1) and (k == rows - i - 1 or k == rows + i - 1):
            print " * ",
        elif i == rows - 1:
            if k % 2 == 0:
                print " * ",
            else:
                print "   ",
        else:
            print "   ",
    print "\n"
#............................................
import os,sys
 
ret = os.access('test/foo.txt',os.F_OK)
print "F_OK - 返回值:%s" % ret
 
ret = os.access('test/foo.txt',os.R_OK)
print "R_OK - 返回值:%s" % ret
 
ret = os.access('test/foo.txt',os.W_OK)
print "W_OK - 返回值:%s" % ret
 
ret = os.access('test/foo.txt',os.X_OK)
print "X_OK - 返回值:%s" % ret
#..........................................<br>
import os, sys
 
path = "test/"
 
# 查看当前工作目录
retval = os.getcwd()
print "当前工作目录为 %s" % retval
 
# 修改当前工作目录
os.chdir( path )
 
# 查看修改后的工作目录
retval = os.getcwd()
 
print "目录修改成功 %s" % retval
#........................................<br>
import os, sys
 
dirPath = "test/" 
print '移除前test目录下有文件:%s' %os.listdir(dirPath)
#判断文件是否存在
if(os.path.exists(dirPath+"foo.txt")):
    os.remove(dirPath+"foo.txt")
    print '移除后test 目录下有文件:%s' %os.listdir(dirPath) 
else:
    print "要删除的文件不存在!"
#...................................................<br>
import os,sys
import shutil
dstPath="test/"
 
print "目录删除前: %s"  % os.listdir(dstPath)
#递归的删除目录及文件
#shutil.rmtree('test/aa')
#以下两个函数用于删除空目录文件
os.rmdir("test/aa")
#os.removedirs("test/aa")
print "目录删除后: %s"  % os.listdir(dstPath)
#.................................................<br>
class Employee:
    empCount = 0
    def __init__(self,name,salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1
 
    def displayCount(self):
        print "Total Employee %d " % Employee.empCount
    def displayEmployee(self):
        print "Name:" , self.name, ",Salary: ", self.salary
 
emp1 = Employee("yuan", 3000)
emp2 = Employee("qiang",4000)
#添加属性
emp1.age = 7
emp2.age = 8
#删除对象emp1的属性
#del emp1.age
emp1.displayEmployee()
emp2.displayEmployee()
print "Total emploeey %d" % Employee.empCount
print "emp1 is %d years old" %emp1.age
print "Employee.__doc__:",Employee.__doc__
print "Employee.__name__:",Employee.__name__
print "Employee.__module__:",Employee.__module__
print "Employee.__bases__:",Employee.__bases__
print "Employee.__dict__:",Employee.__dict__
#.......................................................
 
#析构函数
 
class Point:
    def __init__(self,x = 0,y = 0):
        self.x = x
        self.y = y
    def __del__(self):
        class_name = self.__class__.__name__
        print class_name ,"销毁"
 
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1),id(pt2),id(pt3) #打印出对象的
#调用析构函数进行对象的销毁
del pt1
del pt2
del pt3
#................................................<br>
class Parent:
    parentAttr = 100
    def __init__(self):
        print "调用父类构造函数"
 
    def parentMethod(self):
        print "调用父类方法"
 
    def setAttr(self,attr):
        Parent.parentAttr = attr
 
    def getAttr(self):
        print "父类属性:",Parent.parentAttr
    def aa(self):
        print "调用父类aa"
 
class Child(Parent):
    def __init__(self):
        print "调用子类构造函数"
 
    def childMethod(self):
        print "调用子类方法"
    def aa(self):
        print "调用子类aa"
 
c = Child()    #实例化子类
c.childMethod()
c.parentMethod()
c.setAttr(200)
c.getAttr()
c.aa()
#......................................
#元素符重载
 
class Vector():
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def __str__(self):
        return 'Vector (%d,%d)' %(self.a,self.b)
    def __add__(self, other):
        return Vector(self.a +other.a,self.b+other.b)
 
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1+v2
#....................................................<br>
class JustCounter:
    __secretCount = 0  #私有成员
    publicCount = 0    #公有成员
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print self.__secretCount
 
counter = JustCounter()
counter.count()
counter.count()
print counter.publicCount
#print counter.__secretCount  #报错,私有成员,不能通过对象进行访问
print counter._JustCounter__secretCount  #可以通过object._className__attrName 这样组合的方式进行访问私有成员
#.............................................<br>
#re成员函数match和search
 
import re
print (re.match("www","www.baidu.com").span())
print (re.match("baidu","www.baidu.com"))
#........................................<br>
import re
 
line = "Cats are smarter than dogs"
 
matchObj = re.search('dogs',line,re.M|re.I)
 
if matchObj:
    print "search----matchObj.group(): ", matchObj.group()
else:
    print "No match!"
 
matchObj = re.match('dogs',line,re.M|re.I)
 
if matchObj:
    print "match----matchObj.group(): ", matchObj.group()
else:
    print "No match!"
#......................................<br>
import re
 
phone = "2004-959-559 # 这是一个国外电话号码"
 
# 删除字符串中的 Python注释
num = re.sub('#.*', "", phone)
print "电话号码是: ", num
 
# 删除非数字(-)的字符串
num = re.sub('\D', "", phone)
print "电话号码是 : ", num
#....................................................<br>
import re
 
def double(matched):
    value = int(matched.group('value'))
    print value
    return str(value*2)
 
s = 'A223D23SSS#2E23236'
print(re.sub('(?P<value>\d+)', double, s))
 
 
# 将匹配的数字乘于 2
def double(matched):
    value = int(matched.group('value'))
    return str(value * 2)
 
 
s = 'A23G4HFD567'
print(re.sub('(?P<value>\d+)', double, s))
#......................................<br>
import thread
import time
 
def print_time(threadname,delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print "%s: %s" %(threadname,time.ctime(time.time()))
 
try:
    thread.start_new_thread(print_time,("Thread-1",2,))
    thread.start_new_thread(print_time,("Thread-2",4,))
except:
    print "Error: unable to start thread"
 
while 1:
   pass
#..............................................<br>
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        print_time(self.name, self.counter, 5)
        print "Exiting" + self.name
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            print "退出线程"
            threading.Thread.exit()
        time.sleep(delay)
        print "%s: %s" % (threadName,time.ctime(time.time()))
        counter -=1
 
thread1 = myThread(1,"Thread-1", 1)
thread2 = myThread(2,"Thread-2", 1)
 
thread1.start()
thread2.start()
 
print "Exitting Main Thread"
 
#......................................................
import threading
import time
 
class myThread(threading.Thread):
    def __init__(self,threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        threadLock.release()
def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print "%s: %s" %(threadName, time.ctime(time.time()))
        counter -= 1
threadLock = threading.Lock()
threads = []
 
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
 
thread1.start()
thread2.start()
 
threads.append(thread1)
threads.append(thread2)
 
for t in threads:
   t.join()
print "Exiting Main Thread"
#..........................................................<br>
import Tkinter
top = Tkinter.Tk()
top.mainloop()
#......................................................<br>
from Tkinter import *
root = Tk()
li = ['C','python','php','html','SQL','java']
movie = ['CSS','jQuery','Bootstrap']
listb = Listbox(root)
listb1 = Listbox(root)
for item in li:
    listb.insert(0,item)
 
for item in movie:
    listb1.insert(1,item)
 
listb.pack()
listb1.pack()
root.mainloop()
#.....................................................<br><br>
#1,2,3,4组成多少种不同的三位数(个位,十位,百位数字各不相同)
count = 0
for a in range(1,5):
    for b in range(1,5):
        for c in range(1,5):
            if a != b and a != c and b != c:
                count += 1
                print a,b,c
print "共%d种组合" %count
#....................................................<br><br>
while True:
    Profit = raw_input("请输入本月的利润:")
    if Profit.isdigit():
        Profitint = int(Profit)
 
        if Profitint <=100000:
            bonus = Profitint * 0.1
        elif Profitint > 100000 and Profitint < 200000:
            bonus = (Profitint - 100000) * 0.075 + 100000 *0.1
        elif Profitint >= 200000 and Profitint < 400000:
            bonus = (Profitint - 200000) * 0.05 + 10000 +7500
        elif Profitint >= 400000 and Profitint < 600000:
            bonus = (Profitint - 400000) * 0.03 + 10000 + 7500 + 10000
        elif Profitint >= 600000 and Profitint < 1000000:
            bonus = (Profitint - 600000) * 0.015 + 10000 + 7500 + 10000+6000
        else:
            bonus = (Profitint - 1000000) * 0.01 + 10000 + 7500 + 10000+6000 + 3000
        print bonus
    elif Profit == 'q':
        exit(0)
    else:
        print "您输入的内容不合法!"
#'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#判断输入的日期是一年种的第几天
 
print "please input Date:"
while True:
    year = raw_input("year:")
    if year.isdigit() == 0:
        print "输入的年份不合法,请重新输入!"
    else:
        yearint = int(year)
        break
while True:
    month = raw_input("month:")
    if month.isdigit() == 1:
        monthint = int(month)
        if 1<= monthint <=12:
            break
        else:
            print "输入的月份不合法,请重新输入!"
            continue
    else:
        print "输入的月份不合法,请重新输入!"
        continue
while True:
    day = raw_input("day:")
    if month.isdigit() == 1:
        dayint = int(day)
        if dayint in (1,3,5,7,8,10,12):
            if 1<= dayint <=31:
                break
            else:
                print "输入的日期不合法,请重新输入!"
                continue
        elif dayint in (4,6,9,11):
            if 1<= dayint <=30:
                break
            else:
                print "输入的日期不合法,请重新输入!"
                continue
        else:
            if yearint%4 == 0 and yearint%100 != 0 or yearint%400 ==0:
                if 1<= dayint <= 29:
                    break
                else:
                    print "输入的日期不合法,请重新输入!"
                    continue
            else:
                if 1 <= dayint <= 28:
                    break
                else:
                    print "输入的日期不合法,请重新输入!"
                    continue
 
    else:
        print "输入的日期不合法,请重新输入!"
        continue
 
if yearint%4 == 0 and yearint%100 != 0 or yearint%400 ==0:
    totalday= [31,60,91,121,152,182,213,244,274,305,335,366]
else:
    totalday = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
 
if int(month) == 1:
    days = dayint
else:
    days = totalday[int(month)-2] + dayint
print "这是今年的第 %d 天" % days
#..........................................................
<br>#排序<br>
l =[]
for i in range(1,4):
    x = int(raw_input('integer:'))
    l.append(x)
l.sort()
print l
#...............................................<br>
# 使用递归
def fib(n):
    if n == 1 or n == 2:
        return 1
    return fib(n - 1) + fib(n - 2)
 
 
# 输出了第10个斐波那契数列
print fib(10)
 
#.................................................
a = [1,2,3,4,5]
b = []
 
for i in range(0,len(a)):
    b.append(a[i])
print b
'''
#乘法口诀
'''
for i in range(1,10):
    for j in range(1,i+1):
        print "%d*%d=%d" %(i,j,i*j),
    print
#.................................................<br>
import time
myD = {1:'a',2:'b'}
for key,value in dict.items(myD):
    print key,value
    time.sleep(1)
#......................................................<br>
import time
print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
 
time.sleep(1)
 
print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
#......................................................<br>
f1 = 1
f2 = 1
for i in range(1,22):
    print "%14ld %14ld" %(f1,f2),
    if(i % 3) == 0:
        print " "
    f1 = f1+f2
    f2 = f1+f2
#................................................................<br>
flag = 0
count = 0
for i in range(101,200):
    for j in range(2,i):
        if i % j == 0:
            flag = 1
    if flag == 0:
        print i
        count +=1
    else:
        flag = 0
print "total :%d " %count
#.......................................................<br>
for a in range(1,10):
    for b in range(0,10):
        for c in range(0,10):
            if a**3 + b**3 + c**3 == c +b*10+a*100:
                print c +b*10+a*100
#...............................................<br>
import datetime
 
if __name__ == "__main__":
    print(datetime.date.today().strftime('%d/%m/%Y'))
 
    time1 = datetime.date(1941,1,5)
    print(time1.strftime('%d/%m/%Y'))
 
    #在time1的时间上加一天
    time2 = time1 + datetime.timedelta(days=1)
    print(time2.strftime("%d/%m/%Y"))
 
    time3 = time2.replace(month=time2.month+1)
    print(time3.strftime('%d/%m/%Y'))
#..........................................................<br>
#计算输入字串中英文字母,空格,数字和其他字符的个数
alphacount = 0
digitcount = 0
spacecount = 0
elsecount = 0
string = raw_input("please input string:")
for s in string:
    if s.isdigit():
        digitcount += 1
    elif s.isalpha():
        alphacount += 1
    elif s.isspace():
        spacecount += 1
    else:
        elsecount += 1
 
print "数字字符共%d个" % digitcount
print "字母字符共%d个" % alphacount
print "空字符共%d个" % spacecount
print "其他字符共%d个" % elsecount
#...................................................<br>
num = int(raw_input("please input the number:"))
amount = int(raw_input("please input the amount:"))
total = 0
num1 = 0
for i in range(0,amount):
     num1 += num*(10**i)
     total = total + num1
     print num1
print total
#.................................................................<br>
#一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
total = 0
a = []
for num in range(2,1001):
    for i in range(1,num):
        if num % i == 0:
            total = total + i
            a.append(i)
 
    if total == num:
        print total
        print a
    total = 0
    a = []
#.............................................<br>
num = 1
for i in range(1,10):
    num = num*2+2
print num
#....................................................<br>
for a in ['x','y','z']:
    for b in ['x', 'y', 'z']:
        for c in ['x', 'y', 'z']:
            if(a!=b)and(b!=c)and(c!=a) and (a!='x') and (c!='x') and (c!='z'):
                print 'a和%s比赛,b和%s比赛,c和%s比赛' %(a,b,c)
#...........................................................<br>
a1 = 2.0
a2 = 3.0
b1 = 1.0
b2 = 2.0
total = 0.0
for i in range(1,20):
    if i == 1:
        total = total + a1/b1+a2/b2
    else:
        temp = a1 + a2
        a1 = a2
        a2 = temp
 
        temp = b1 + b2
        b1 = b2
        b2 = temp
        total = total + a2 / b2
print total
#.........................................
 
#翻转字串输出
def Reverse(str,len):
    if len == 0:
        return
    print str[len-1],
    len = len -1
    Reverse(str,len)
string = raw_input("please input string:")
len = len(string)
Reverse(string,len)
#........................................................<br>
def Age(n):
    if n == 1:
        return 10
    else:
        return Age(n-1)+2
 
print Age(5)
#..........................................<br>
num = int(raw_input("number:"))
count = 0
n = num
while True:
    a = n%10
    print a,
    count += 1
    n = n/10
    if n == 0:
        break
print "此数是%d位数" % count
#..................................................<br>
#判断输入的数字是否为回文数
num = raw_input("number:")
lenth = len(num)
flag = True
for i in range(lenth/2+1):
    if num[i] != num [lenth-i-1]:
        flag = False
if flag == False:
    print "%d不是回文数" % int(num)
else:
    print "%d是回文数" % int(num)
#......................................................<br>
Firstletter = raw_input("week:")
 
if Firstletter == "s" or Firstletter == "S":
    Secondletter = raw_input("please input the second letter:")
    if Secondletter == "u":
        print "today is sunday!"
    elif Secondletter == "a":
        print "today is saturday!"
    else:
        print "data error!"
elif Firstletter == "m" or Firstletter == "M":
    print "totay is monday!"
elif Firstletter == "T" or Firstletter == "t":
    Secondletter = raw_input("please input the second letter:")
    if Secondletter == "u":
        print "today is Tuesday!"
    elif Secondletter == "h":
        print "today is Thursday!"
    else:
        print "data error!"
elif Firstletter == "W" or Firstletter == "w":
    print "today is Wednesday!"
elif Firstletter == "F" or Firstletter == "f":
    print "today is Friday!"
else:
    print "data error!"
#...................................................
<br>#倒序输出列表元素<br>
a = ['one', 'two', 'three']
for i in a[::-1]:
    print i
'''
'''
def export():
    L = [1,2,3,4,5]
    s1 = ','.join(str(n) for n in L)
    print s1
if __name__ == "__main__":
    export()
#.....................................................
#设置文本颜色
class bcolors:
    HEADER = "\033[95m"
    OKBLUE = "\033[94m"
    OKGREEN = "\033[91m"
    WARNING = "\033[93m"
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
print bcolors.OKGREEN + "警告的颜色字体" + bcolors.ENDC
#.......................................................
<br>#二维数组
if __name__ == "__main__":
    a = []
    sum = 0.0
    for i in range(3):
        a.append([])  #列表里面包含列表形成二维数组
        for j in range(3):
            a[i].append(float(raw_input("input num:\n")))
    for i in range(3):
        sum += a[i][i]
    print sum
#输出二维数组
for i in range(3):
    print a[i]
#..........................................................<br>
#给已经排序的列表中插入新的元素
num = int(raw_input("number:"))
a = [1,3,4,5,12,13,23,34,45,56,0]#最后一个0作为占位符,以防止列表插入一个元素时越界
lenth = len(a)-1
 
if num >=a[lenth -1]:
    a[lenth] = num
else:
    for i in range(lenth):
        if num < a[lenth-i-1]:
            a[lenth-i] = a[lenth-i-1]
            a[lenth-i-1] = num
print a<br>#...........................................................<br>
a = [1,2,3,4,5]
lenth = len(a)
for i in range(lenth):
    print a[lenth-i-1]
'''
'''
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
 
Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]
 
total = [[0,0,0],
         [0,0,0],
         [0,0,0]]
for i in range(3):
    for j in range(3):
        total[i][j] = X[i][j] + Y[i][j]
for i in range(3):
    print total[i]
#.................................................<br>
MAXIMUM = lambda x,y : (x>y)*x + (x<y)*y
MINMUM = lambda x,y:(x>y)*x + (x<y)*x
if __name__ == '__main__':
    a = 10
    b = 20
    print "The largar one is %d " % MAXIMUM(a,b)
    print "The lower one is %d" % MINMUM(a,b)<br>#..................................................
if __name__ == "__main__":
    from Tkinter import *
    canvas = Canvas(width =800,height = 600,bg = "yellow")
    canvas.pack(expand= YES,fill=BOTH)
    k = 1
    j = 1
    for i in range(0,26):
        canvas.create_oval(310-k,250-k,310+k,250+k,width=1)
        k += j
        j += 0.3
    mainloop()
#......................................................<br>
if __name__ == '__main__':
    import turtle
    turtle.title("画圆")
    while True:
        turtle.setup(800,800,100,100)
        pen=turtle.Turtle()
        pen.color("blue")
        pen.width(5)
        pen.shape("turtle")
        pen.speed(1)
        pen.circle(100)
#.........................................................<br>
#画直线
if __name__ == "__main__":
    from Tkinter import *
 
    canvas = Canvas(width=300, height=300,bg = "green")
    canvas.pack(expand=YES,fill=BOTH)
    x0 = 263
    y0 = 263
    y1 = 275
    x1 = 275
    for i in range(19):
        canvas.create_line(x0,y0,x0,y1,width=1, fill='red')
        x0 = x0 - 5
        y0 = y0 - 5
        x1 = x1 + 5
        y1 = y1 + 5
    x0 = 263
    y1 = 275
    y0 = 263
    for i in range(21):
        canvas.create_line(x0,y0,x0,y1,fill='red')
        x0 += 5
        y0 += 5
        y1 += 5
 
 
    mainloop()
#......................................................................<br>
#画正方形
if __name__ == "__main__":
    from Tkinter import *
    root = Tk()
    root.title('Canvas')
    canvas = Canvas(root,width = 400,height = 400,bg = "yellow")
    x0 = 263
    y0 = 263
    y1 = 275
    x1 = 275
    for i in range(19):
        canvas.create_rectangle(x0,y0,x1,y1)
        x0 -= 5
        y0 -= 5
        x1 += 5
        y1 += 5
    canvas.pack()
    root.mainloop()
#................................................................
#画椭圆
if __name__ == "__main__":
    from Tkinter import *
    x = 360
    y = 160
    top = y -30
    bottom = y -30
    canvas = Canvas(width = 400,height = 600,bg = 'white')
    for i in range(20):
        canvas.create_oval(250-top,250 - bottom,250+top,250+bottom)
        top -= 5
        bottom += 5
    canvas.pack()
    mainloop()
#.....................................................................<br>
import math
class PTS:
    def __init__(self):
        self.x = 0
        self.y = 0
points = []
 
def LineToDemo():
    from Tkinter import *
    screenx = 400
    screeny = 400
    canvas = Canvas(width = screenx,height = screeny,bg = 'white')
 
    AspectRatio = 0.85
    MAXPTS = 15
    h = screeny
    w = screenx
    xcenter = w / 2
    ycenter = h / 2
    radius = (h - 30) / (AspectRatio * 2) - 20
    step = 360 / MAXPTS
    angle = 0.0
    for i in range(MAXPTS):
        rads = angle * math.pi / 180.0
        p = PTS()
        p.x = xcenter + int(math.cos(rads) * radius)
        p.y = ycenter - int(math.sin(rads) * radius * AspectRatio)
        angle += step
        points.append(p)
    canvas.create_oval(xcenter - radius,ycenter - radius,
                       xcenter + radius,ycenter + radius)
    for i in range(MAXPTS):
        for j in range(i,MAXPTS):
            canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y)
 
    canvas.pack()
    mainloop()
if __name__ == '__main__':
    LineToDemo()
#....................................................<br>
def Maxnum(n,lenth):
    max = n[0]
    for i in range(lenth):
        if n[i] > max:
            max = n[i]
            index = i
    return index
 
def Minnum(n,lenth):
    min = n[0]
    for i in range(lenth):
        if n[i] < min:
            min = n[i]
            index = i
    return index
 
if __name__ == "__main__":
    a = []
    for i in range(5):
        num = int(raw_input("number:"))
        a.append(num)
    print a
    lenth = len(a)
    maxindex = Maxnum(a,lenth)
    minindex = Minnum(a,lenth)
    a[0],a[maxindex] = a[maxindex],a[0]
    a[lenth-1],a[minindex] = a[minindex],a[lenth-1]
    print a
#.........................................................<br>
from collections import deque
 
m = 3
a = [1,2,3,4,5,6,7]   #7 个数
f = deque(a)
f.rotate(m)
print list(f)
#.....................................................<br>
if __name__ == "__main__":
    a = [1,3,2]
    b = [3,4,5]
    a.sort()
    print a
    print a + b
    a.extend(b) #连接两个列表
    print a
#......................................................
num = int(raw_input("number:"))
sum = 0.0
for i in range(1,num+1):
    if num%2 == 0 and i%2 == 0:
        sum = sum + 1.0/i
    elif num%2 != 0 and i%2 != 0:
        sum = sum + 1.0/i
print sum
#............................................................<br>
if __name__ == "__main__":
    person = {"li":18,"wang":13,"zhang":20,"sun":30}
    m = 'li'
    for key in person.keys():
        if person[m] < person[key]:
            m = key
print "%s,%d" %(m,person[m])
#..........................................................<br>
if __name__ == '__main__':
    str1 = raw_input('input string:\n')
    str2 = raw_input('input string:\n')
    str3 = raw_input('input string:\n')
    print str1, str2, str3
 
    if str1 > str2: str1, str2 = str2, str1
    if str1 > str3: str1, str3 = str3, str1
    if str2 > str3: str2, str3 = str3, str2
 
    print 'after being sorted.'
    print str1, str2, str3
#.....................................................
my_lambda = lambda arg:arg+1
result = my_lambda(2)
print result

  

posted @   轻轻的吻  阅读(654)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示