###### python -V :Python 2.7.16
#/usr/bin/python
# -*- coding: utf-8 -*-
print('Hello World.')
#-----------------------------
mystr = "\n" # a newline character
mystr = r"\n" # two characters, \ and n
#-----------------------------
mystr = "Jon 'Maddog' Orwant" # literal single quote inside double quotes
print mystr
mystr = 'Jon "Maddog" Orwant' # literal double quote inside single quotes
print mystr
#-----------------------------
mystr = 'Jon \'Maddog\' Orwant' # escaped single quote
print mystr
mystr = "Jon \"Maddog\" Orwant" # escaped double quote
print mystr
#-----------------------------
mystr = """
This is a multiline string literal
enclosed in triple double quotes.
"""
#mystr = "I want to see if " will be shown.\n"
#print('mystr = """ will be shown as:')
#MC:failed
mystr = '''
And this is a multiline string literal
enclosed in triple single quotes.
'''
#mystr = 'I want to see if ' will be shown.\n'
#print('mystr = """ will be shown as:')
#MC:failed
#-----------------------------
print('\n--------\n This is test for List\n---------\n')
MC_list=['Rob','Tyler','Ahmed']
print ('My Language partners are:')
print(MC_list[2])
#print('I have',len(MC_list),'language partners in total')
print('My last is:')
print(MC_list[len(MC_list)-1])
print(len(MC_list)-1)
print(MC_list[-1])
print('I have new language partners now:')
MC_list.append('Chritine')
print ('My Language partners are:')
print(MC_list)
MC_list.insert(2,'Ken')
print ('My Language partners are:')
print(MC_list)
MC_list.pop()
print ('My Language partners are:')
print(MC_list)
MC_list.pop(2)
print ('My Language partners are:')
print(MC_list)
print('\n------\nITs time for Tutle.\n----\n')
MC_t1=('M1','M2','M3')
print(MC_t1)
MC_t2=(3,)
print(MC_t2)
MC_t3=('MC3')
print(MC_t3)
print('\n------\nITs time for Conditions:\n----\n')
age=42
print('How Old are you?')
#age=input()
if age<=40:
print('you are',age,'years old.You must be uslesss')
print('But you still have lots of opportunities.')
elif age<=41:
print('No worries, you might still have chance in your life')
else:
print("you are",age," years old alreadt. You are as good as dead.")
print('\n------\nITs time for Loops:\n----\n')
print ('My Language partners in for--in loop are:')
for MC_for in MC_list:
print(MC_for)
# to add 1 - 10
sum=0
for i in (1,2,3,4,5,6,7,8,9,10):
sum=sum+i
print('Now,time to show the turth,1++10 is:')
print(sum)
sum=0
for i in range(101):
# print(i)
sum=sum+i
print('Now,time to show the turth,1++100 is:')
print(sum)
print ('The total of even integer numbers between 0-100 is:')
sum=0
number=100
while number>0:
sum=sum+number
number=number-2
print(sum)
print ('The total of odd integer numbers between 0-100 is:')
sum=0
number=99
while number>0:
sum=sum+number
number=number-2
print(sum)
print ('To demestrate the function of continue in a while loop')
print ('The total of odd integer numbers between 0-100 is:')
sum=0
number=100
while number>0:
number=number-1
if number % 2 == 0:
continue
sum=sum+number
print(sum)
print('\n------\nIt\'s time for dict:\n----\n')
MC_dict={'Ken':62,'Ahmed':52,'Robert':39,'Tyler':35}
print("Hello Tyler,how old are you?")
print(MC_dict['Tyler'])
print('use "in" to test if a key exist.')
if 'Ken' in MC_dict:
print('Hello Ken, you are:')
print(MC_dict['Ken'])
else:
print('no Ken1 in thd dict.Plese double check.')
print('use "get" to test the existence or to insert an element if notavaliable.')
if MC_dict.get('Ken1'):
print('Hello Ken, you are:')
print(MC_dict['Ken'])
else:
print(MC_dict.get('Ken1',63))
print('Hello Ken1, You are getting older,hahaha.')
#print(MC_dict['Ken1'])
print('\n------\nIt\'s time for set:\n----\n')
MC_set=set([1,2,3,4,5,6,6,6,4,3])
#PUTPUT:set([1, 2, 3, 4, 5, 6])
print('This is Set MC_set. its elemesnt are:')
print(MC_set)
print('I am going to add new elment. I\'m going to add many times. But i guess it won\'y work?')
MC_set.add('Vert')
MC_set.add('Rough')
MC_set.add('Vert')
MC_set.add('Rough')
MC_set.add('Rough')
MC_set.add(8)
MC_set.add(7)
MC_set.add(7)
MC_set.add(7)
print(MC_set)
#=== OUTPUT:set([1, 2, 3, 4, 5, 6, 7, 8, 'Rough', 'Vert'])
print('to remove with function remove:')
MC_set.remove(7)
print(MC_set)
print('To use set to realise the AND and OR:')
MC_set1=set([10,20,30,40,50,60])
MC_set2=set([10,70])
print("NOW Either")
##10
print(MC_set1 | MC_set2)
print('NOW BOTH')
print(MC_set1 & MC_set2)
##set([50, 20, 70, 40, 10, 60, 30])
MC_set1=set(['Bleu','Rough','Rough','Black'])
MC_set2=set(['Black','Red'])
print("NOW Either")
print(MC_set1 | MC_set2)
#set(['Bleu', 'Rough', 'Black', 'Red'])
print('NOW BOTH')
print(MC_set1 & MC_set2)
# Black
print('你可以支持中文吗?')
##2021,11,14
print('\n------\nIt\'s time for Funtions:\n----\n')
print('\n------\nIt\'s time for abs,max,min :\n----\n')
print(abs(-23))
print(min(1,3,5,4,2,4,3,2,3,3))
print(max(1,3,5,4,2,4,3,2,3,3,95736))
def MC_abs(x):
if x>0:
return x
else:
return -x
print ("-256 abs is:")
print(MC_abs(-256))
print('\n------\nIt\'s time for None function:pass:\n----\n')
def MC_non():
pass
MC_pass=42
if MC_pass>42:
pass
else:
print('You are so old.')
print('checking canshu:')
print(abs(-23))
#print(abs('-23'))
print('And how about my funtion MC_abs?')
print(MC_abs('-256')) # NON, it doesnt cheak type... BAD bad bad.
print('To have more than one returns')
import math
def MC_move(x,y,step,angle=0):
mc_x=x+step*math.cos(angle)
mc_y=y-step+math.sin(angle)
return mc_x,mc_y
print (MC_move(60,80,30,math.pi/7))
print(math.pi)
# positional arguments:
print ('The square of x:')
def MC_power(x):
return x*x
print(MC_power(5))
# to define two positional arguments to handle any times power .
print ('The power of x:')
def MC_power(x,n):
s=1
while n>0:
n=n-1
s=s*x
return s
print(MC_power(2,12))
# the default argument:
print ('The default argument in power function :')
def MC_power(x,n=2):
s=1
while n>0:
n=n-1
s=s*x
return s
print(MC_power(2,9))
print(MC_power(9))
# to calcuate the total of square of a2+b2...."
print(" the total of square of a2+b2(1-10)....")
def MC_cal_sqr(numbers):
s=0
for n in numbers:
s=s+n*n
return s
print(MC_cal_sqr([1,2,3,4,5,6,7,8,9,10]))
# to upgrade this funtion using chaning? argument *
print(" the total of square of (1-10) with using various arguments....")
def MC_cal_sqr(*numbers):
s=0
for n in numbers:
s=s+n*n
return s
print(MC_cal_sqr(1,2,3,4,5,6,7,8,9,10))
# to change a list of items into a various argument.
print('to change a list of items into a various argument *')
chaning_list=[1,2,3,4,5,6,7,8,9,10]
print(MC_cal_sqr(*chaning_list))
#key arguments **
print('Key Arguments:')
def MC_keyv(name,age,**extra):
print('name:',name, 'age:' ,age, 'other:', extra)
print(MC_keyv('Tyler','34',City='US',Hobby='eating'))
# to use dict as a key argument:
MC_extra={'City':'Beijing','job':'waiting for Death','Hope':'Nothing'}
print(MC_keyv('MMCC','42',**MC_extra))
# to check if the key argument exsits:
def MC_keyv(name,age,**extra):
if 'City' in extra:
pass
if 'Hobby' in extra:
pass
print('name:',name, 'age:' ,age, 'other:', extra)
print(MC_keyv('Tyler','34',City='US',Hobby='eating'))
# to limit that only the listed argument are allowed
#def MC_keyv(name,age,*,City,Hobby):
# print('name:',name,'age:',age,'City:'City,'Hbby:',Hobby)
#print(MC_keyv('Tyler','34',City='US',Hobby='eating'))
print('\n------\nIt\'s time for 递归:\n----\n')
def fact(n):
if n==1:
return 1
return n*fact(n-1)
print ('Fact(4) is:')
print(fact(4))
print('\n------\nIt\'s time for 切片 slice:\n----\n')
List_Slice=['Rough','Bleu','Blanc','Noir','Pink','Purple','Green']
print("The referring elements of List_Slience is:",List_Slice[-5:-4])
#0-99
List_Slice=range(100)
#前十个元素
print("The referring elements of List_Slience is:",List_Slice[0:10])
print("The referring elements of List_Slience is:",List_Slice[-20:-1])
#取倒数9个
print("The referring elements of List_Slience is:",List_Slice[-9:])
#前20个,每三个取一个
print("The referring elements of List_Slience is:",List_Slice[:20:3])
#所有列,每6个取一个
print(" one per six:",List_Slice[::6])
#to copy the whole list:
print(List_Slice[:])
#直接操作字符串:打出前三个字符
print('ABCDEFG'[0:3])
#output: ABC
print('\n------\nIt\'s time for 迭代Iteration:\n----\n')
# 迭代list 用for in 的方式
List_Iteration=range(5)
for i in List_Iteration:
print(i)
print('\n')
#迭代 dict 默认为 key:
Dict_Iteration={'Ken':'Aus','Rob':'Bri','Ahmed':'Fra','Tyler':'US'}
for key in Dict_Iteration:
print(key)
print('\n')
# 迭代 dict 中的value:
for value in Dict_Iteration.values():
print(value)
print('\n')
#迭代 dict 中的key anb value:
for key,value in Dict_Iteration.items():
print(key,value)
#迭代字符串
for str_m2 in 'HelloWorldBonjourleMonde':
print(str_m2)
#测试可否迭代。 测试失败,来日方长。
#from collections.abc import Iterable
#print(isinstance('ABC',Iterable))
#实现迭代时的下标问题:enumerate
for i,str_3 in enumerate('BONJOUR'):
print(i,str_3)
# 同时引用两个变量。
for i,j in [(1,4),(2,8),(3,12)]:
print(i,j)
###列表生成式 List Comprehensions
print('\n------\nIt\'s time for 列表生成式 List Comprehensions:\n----\n')
# to generate 1,2,....11 range(1,11)
print('to generate intergers with range.\n')
#0-4:
print(range(5))
#1-5:
print(range(1,6))
# to generate 1*1,2*2...11*11 用循环
L=[]
for i in range(1,12):
L.append(i*i)
print(L)
#1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121
#不用循环,用列表生成式 ,达到上方结果
L=[x*x for x in range(1,12)]
print(L)
#output: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121
#try again. 2x+5
L=[2*x+5 for x in range(1,11)]
print(L)
#7, 9, 11, 13, 15, 17, 19, 21, 23, 25
# to add a conditional to get the odd numbers.
L=[x*x for x in range(1,11) if x%2==0]
print(L)
#4, 16, 36, 64, 100 (that is: 2,4,6,8,10)
# To get two combinded elements:
L=[m+n for m in 'ABC' for n in 'EDF']
print(L)
#
D={'A':'Y','B':'N','C':'NA'}
L=[k+'='+v for k,v in D.items()]
print(L)
#'A=Y', 'C=NA', 'B=N'
# to lowcase letters.
L=['Bonjour','le','Monde']
print(L)
#print(s.lower() for s in L) ATTENYTION: ERROR:
print([s.lower() for s in L])
print('\n------\nIt\'s time for 生成器generator:\n----\n')
#to define a genertor by using () instead of [] of a List
G=(x*x for x in range(1,11) if x%2==0)
print(G)
# to print the element of a generator.: next()
#(next(G))
#print(next(G))
#print(next(G))
#print(next(G))
# It's more sensible and more common to use for loop to list the element:
for n in G:
print(n)
# to realise Fibonacci with function: 1 1 2 3 5 8 13 21....
def Fib(max):
n,a,b=0,1,1
while n
print(a)
a,b=b,a+b
n=n+1
return 'done_Function\n'
print(Fib(6))
# to transfer the above funtion to operation:
def Fib(max):
n,a,b=0,1,1
while n
yield a
a,b=b,a+b
n=n+1
#return 'done' 加这句就报错。
print(Fib(6))
#define wield.
def wield():
print('First:')
yield ' un'
print('Second:')
yield ' deux'
print('Thrid:')
yield ' trois-Done\n'
w=wield()
print(next(w))
print(next(w))
print(next(w))
print('------\n')
print(next(wield()))
print(next(wield()))
print(next(wield()))
# to catch exception with try--exception:
'''def Fib1(max):
n,a,b=0,1,1
while n
yield a
a,b=b,a+b
n=n+1
return 'FIN'
G=Fib1(8)
while True:
try:
x=next(G)
except StopIteration as e:
print('The Generator return value:',e.value)
break
'''
print('The next page.')
# to test Iterable:
from collections import Iterable
print(isinstance([],Iterable))
print(isinstance({},Iterable))
print(isinstance('ABC',Iterable))
print(isinstance([x*x for x in range(11)],Iterable))
print(isinstance(100,Iterable))
print('\n')
#to test Iterator
from collections import Iterator
print(isinstance((x*x for x in range(11)),Iterator))
print(isinstance([x*x for x in range(11)],Iterator))
print(isinstance([],Iterator))
print(isinstance({},Iterator))
print(isinstance('ABC',Iterator))
print('\n')
# to transer interable to intertor:
print(isinstance(iter([]),Iterator))
print(isinstance(iter({}),Iterator))
print('\n------\nIt\'s time for 高阶函数:Higher-order function:\n----\n')
print(abs(-300))
print(abs)
#高级函数,就是把另一个函数作为参数来调用。函数套函数
f=abs
def absolutely_add(x,y,f):
result=f(x)+f(y)
return result
print(absolutely_add(3,-4,f))
'''
报错。你说是为什么?
f=lower
def change_upper(s,f):
result=f(s)
return result
print(change_upper('Bonjour',f))
'''
print(list)
print('\n------\nIt\'s time for map:\n----\n')
def f(x):
return x*x
L=map(f,[1,2,3,4,5,6,7,8])
print(L)
#reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
print(reduce)
# 1+2+3+4+5
def add_map(x,y):
return x+y
print(reduce(add_map,[1,2,3,4,5]))
#reduce for 13579
def fn(x,y):
return x*10+y
print(reduce(fn,[1,3,5,7,8,9]))
def chartonum(s):
dig={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8': 8,'9': 9}
return dig[s]
print(chartonum('7'))
print(map(chartonum,'13456'))
print(reduce(fn,map(chartonum,'13456')))
# 整理一下,形成一个很酷的函数,叫strtoint
print('函数strtoint,可以吧字符转成整数')
from functools import reduce
dig={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8': 8,'9': 9}
def strtoint(s):
def fn(x,y):
return x*10+y
def chartonum(s):
return dig[s]
return reduce(fn,map(chartonum,s))
print(strtoint('23456'))
print('\n------\nIt\'s time for filter:\n----\n')
def Isaodd(i):
if i % 2 == 0:
return i
print(list(filter(Isaodd,[1,2,3,4,5,6,7,8,10,15,14,24,45])))
'''
def non_space(s):
return s and s.strip()
print(non_space(['A','B','',' ','C']))
'''
print('\n------\nIt\'s time for sorted:\n----\n')
print(sorted([12,24,34,13,45,-23,896,-345]))
print(sorted([12,24,34,13,45,-23,896,-345],key=abs))
print(sorted(['Ken','rob','Tyler','ahmed','Sophie','laurence']))
#str_m=['Ken','rob','tyler','ahmed','Sophie','laurence']
print(sorted(['Ken','rob','Tyler','ahmed','Sophie','laurence'], key=str.lower))
#print(sorted("This is a test string from Andrew".split(), key=str.lower))
print(sorted(['Ken','rob','Tyler','ahmed','Sophie','laurence'], key=str.lower,reverse=True))
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
from operator import itemgetter
L2 = sorted(L, key=itemgetter(0))
print(L2)
L3 = sorted(L, key=itemgetter(1))
print(L3)
L4 = sorted(L, key=lambda t: t[1])
print(L4)
L5 = sorted(L, key=itemgetter(1), reverse=True)
print(L5)
print('\n------\nIt\'s time for return a function:\n----\n')
def calc_sum(*argc):
ax=0
for n in argc:
ax=ax+n
return ax
print(calc_sum(1,2,3,4,5))
def lazy_sum(*argc):
def calc_sum():
ax=0
for n in argc:
ax=ax+n
return ax
return calc_sum
print(lazy_sum(5,8))
f=lazy_sum(5,8)
print(f())
print(lazy_sum(5,8)())
print('\n------\nIt\'s time for anonymous functions.:\n----\n')
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
# To define an anonymous function to a defined function.
f_mei=lambda x: x*x*x
print(f_mei)
print(f_mei(2))
print('-------')
#
def fr_m(x):
# tmp=lambda : x*x
# return tmp()
return lambda: x*x
''' def tmp():
return x*x
return tmp()
def build(x, y):
return lambda: x * x + y * y
print(build(2,3))
'''
print(fr_m(2))
print('-------')
List_dec=list(filter(lambda x:x % 2 ==1,range(1,20)))
print(List_dec)
print('\n------\nIt\'s time for partial functions.:\n----\n')
print (int('12306'))
print (int('12306',base=8))
print (int('12306',16))
'''
def int2(x,base=2):
return int(x,base)
print(int2('101010'))
print(int2('11111'))
print(int2('100000000'))
'''
import functools
int2=functools.partial(int,base=2)
print(int2('101010'))
print(int2('11111'))
print(int2('100000000'))
print(int2('100000',base=10))