2018年1月8日 星期一

Python: Get the Python version

Python: Get the Python version

Python Basic: Exercise-2 with Solution

Write a Python program to get the Python version you are using.
A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started.
Version info:
A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is 'alpha', 'beta', 'candidate', or 'final'. The version_info value corresponding to the Python version 2.0 is (2, 0, 0, 'final', 0). The components can also be accessed by name, so sys.version_info[0] is equivalent to sys.version_info.major and so on.
Note : 'sys' module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
Sample Solution:-

print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)
========= RESTART: F:/Python_APSC/py-ex-basic-2.py =============
Python version
3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)]
Version info.
sys.version_info(major=3, minor=5, micro=1, releaselevel='final', serial=0)
>>> 

Python: Print a string in a specified format


Python: Print a string in a specified format

Python Basic: Exercise-1 with Solution

Write a Python program to print the following string in a specific format (see the output).
Sample String: "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are!"
The print statement (Python 2.6) has been replaced with a print() function (Python 2.6), with keyword arguments to replace most of the special syntax of the old print statement .
  • The print() function doesn’t support the “softspace” feature of the old print statement. For example, in Python 2.x, print "A\n", "B" would write "A\nB\n"; but in Python 3.0, print("A\n", "B") writes "A\n B\n".
  • Initially, you’ll be finding yourself typing the old print x a lot in interactive mode. Time to retrain your fingers to type print(x) instead!
  • When using the 2to3 source-to-source conversion tool, all print statements are automatically converted to print() function calls, so this is mostly a non-issue for larger projects.
Examples:
Old: print "The answer is", 3*3
New: print("The answer is", 3*23

Old: print a,           # Trailing comma suppresses newline
New: print(a, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (a, b)       # prints repr((a, b))
New: print((a, b))      # Not the same as print(a, b)
Sample Solution:-


print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!")


================== RESTART: F:/Python_APSC/py-ex-basic-1.py ==================
Twinkle, twinkle, little star, 
How I wonder what you are! 
Up above the world so high, 
Like a diamond in the sky. 
Twinkle, twinkle, little star, 
How I wonder what you are!
>>> 

Python 列舉

Python List: Exercise - 18 with Solution
Write a Python program to generate all permutations of a list in Python.
In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. These differ from combinations, which are selections of some members of a set where order is disregarded.
In the following image each of the six rows is a different permutation of three distinct balls.
Pictorial Presentation
Different permutation of three distinct balls
Sample Solution:-
Python Code:
import itertools
print(list(itertools.permutations([1,2,3])))

Sample Output:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] 


Python - get all permutation of a list w/o repetitions

from itertools import combinations

lis = [1, 2, 3, 4]
for i in range(1, len(lis) + 1):
    #range will return the values 1,2,3,4 in this loop
    print (list(combinations(lis, i)),'\n')

print (list(combinations([1, 2, 3, 4], 3)))


===================== RESTART: F:/Python_APSC/b038-2.py =====================

[(1,), (2,), (3,), (4,)] 

[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] 

[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] 

[(1, 2, 3, 4)] 


[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] 


>>> 

2018年1月7日 星期日

Permutations 列舉





# permutations 列舉法
import itertools
print (list(itertools.permutations([1,2,3,4], 2)))
print (list(itertools.permutations(['j','o','h','n'], 2)))
print (list(itertools.permutations(['j','o','n'], 3)))


=========== RESTART: F:/Python_APSC/b038-2.py ==============
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
[('j', 'o'), ('j', 'h'), ('j', 'n'), ('o', 'j'), ('o', 'h'), ('o', 'n'), ('h', 'j'), ('h', 'o'), ('h', 'n'), ('n', 'j'), ('n', 'o'), ('n', 'h')]
[('j', 'o', 'n'), ('j', 'n', 'o'), ('o', 'j', 'n'), ('o', 'n', 'j'), ('n', 'j', 'o'), ('n', 'o', 'j')]
>>> 

b038: 法老王的石獅子

小安一行人到埃及去探險,意外發現一座金字塔,透過當地學者翻譯石碑上的文字,得知只要將金字塔前幾隻大小不一的石獅子依照某種順序排列,金字塔的大門就會開啟,並且可以得到法老王的寶藏。不過由於這些石獅子的排列方式太多了,所以小安決定依照順序一個一個排列出來,你能幫他列出所有的排列方式嗎?
輸入說明:
輸入一個正整數 N (2<=N<=8),代表有幾個石獅子要排列,而這些石獅子的編號從小到大為 1~N。
輸出說明:
請由小到大輸出所有的排列方式。
範例輸入:
2
範例輸出 :
12
21


#===========================================
'''用子集樹實現全排列'''

# 衝突檢測:無
def conflict(k):
    global n, x, X, a
   
    return False # 無衝突
    
  
# 用子集樹範本實現全排列
def perm(k): # 到達第k個元素
    global n, a, x, X
    
    if k >= n:  # 超出最尾的元素
        print(x)
        #X.append(x[:]) # 保存(一個解)
    else:
        for i in set(a)-set(x[:k]): # 遍歷,剩下的未排的所有元素看作元素x[k-1]的狀態空間
            x[k] = i
            if not conflict(k): # 剪枝
                perm(k+1)


# 測試


print("輸入一個正整數 N (2<=N<=8),代表有幾個石獅子要排列,而這些石獅子的編號從小到大為 1~N。")
print("輸入一個正整數 N (2<=N<=8) --> ")
n=int(input())

a=[]
for i in range (1 , n+1):
    a.append(i)
    
print (a)
print("\n\n")


x = [0]*n   # 一個解(n元0-1陣列)
X = []      # 一組解

perm(0)     # 從x[0]開始






===================== RESTART: F:/Python_APSC/b038-1.py =====================
輸入一個正整數 N (2<=N<=8),代表有幾個石獅子要排列,而這些石獅子的編號從小到大為 1~N。
輸入一個正整數 N (2<=N<=8) --> 
4
[1, 2, 3, 4]



[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 1, 3]
[2, 4, 3, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 1, 2, 3]
[4, 1, 3, 2]
[4, 2, 1, 3]
[4, 2, 3, 1]
[4, 3, 1, 2]
[4, 3, 2, 1]
>>> 

b039: 最終兵器X



 西元2185年,地球人終於有能力征服其他有生物的星球,不過卻受到該星球生物的反擊。於是科學家們發明了一種「最終兵器X」(如下圖),它能自動攻擊左上、上、右上、右、右下、下、左下、左等八個方向的敵人,只要在地圖上放上幾台,就可以不費吹灰之力消滅敵人。

不過很不幸地,它也會把另一台最終兵器X當做是敵人,因此必須精準計算它們的位置,以免它們互相攻擊到對方。經過數學家仔細地計算,發現一個 NxN 的地圖上,最多可以放 N 台最終兵器X,而且每一列只能放一台,你能幫他們找出來怎麼放比較適合嗎?


輸入說明:
輸入一個正整數 N (4<=N<=12),代表要放 N 台的最終兵器X。
輸出說明:
請輸出每種可能的排法,因為每列只能放一個,故只要輸出每列的最終兵器X是放在第幾行就可以了,請依序輸出第一列、第二列、…第N列的位置。
範例輸入:
4
範例輸出 :
2 4 1 3
3 1 4 2


import random
#隨機模組

def conflict(state,col):
    #衝突函數,row為行,col為列
    row=len(state)
    for i in range(row):
        if abs(state[i]-col) in (0,row-i):#重要語句
            return True
    return False
    
def queens(num ,state=()):
    #生成器函數
    for pos in range(num):
        if not conflict(state, pos):
            if len(state)==num-1:
                yield(pos,)
            else:
                for result in queens(num, state+(pos,)):
                    yield (pos,)+result

def queenprint(solution):
    #列印函數
    def line(pos,length=len(solution)):
        return '. '*(pos)+'X '+'. '*(length-pos-1)
    for pos in solution:
        print (line(pos))
        



print("輸入一個正整數 N (4<=N<=12),代表要放 N 台的最終兵器X。")
N=int(input())

for solution in list(queens(N)):
    print (solution)

print ()    
print ( '  total number is '+str(len(list(queens(N)))))
print ( '  one of the range is:\n')
queenprint(random.choice(list(queens(N))))




===================== RESTART: F:/Python_APSC/b039-3.py =====================
輸入一個正整數 N (4<=N<=12),代表要放 N 台的最終兵器X。
4
(1, 3, 0, 2)
(2, 0, 3, 1)

  total number is 2
  one of the range is:

. X . . 
. . . X 
X . . . 
. . X . 
>>> 

  清除項目編譯快取 執行 flutter clean 重新取得套件依賴 執行 flutter pub get 完整重新編譯並執行 flutter run 1. 新增專案套件 (pubspec.yaml) 在 Flutter 專案根目錄下的 pubspec.yaml 中,新增 ...