顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2024年1月8日 星期一

合併

 # d = [1,2,3,4,5,10,8,6,2,123,256,379,1014,11,22]

#最小二個合併

d = list(range(1,11))

print(d)

cost = 0

for i in range(len(d)-1):

    t = d[0]+d[1]

    c = abs(d[0]-d[1])

    cost = cost + c

    d.append(t)

    d.remove(d[0])

    d.remove(d[0])

    d.sort()

    print(d,cost)


# 最大跟最小合併

d = list(range(1,11))

print(d)

cost = 0

for i in range(len(d)-1):

    t = d[0]+d[-1]

    c = abs(d[0]-d[-1])

    cost = cost + c

    d.append(t)

    d.remove(d[0])

    d.remove(d[-2])

    d.sort()

    print(d,cost)


#最小跟中間以後第1個合併

d = list(range(1,11))

print(d)

cost = 0

for i in range(len(d)-1):

    m = len(d)//2

    t = d[0]+d[m]

    c = abs(d[0]-d[m])

    cost = cost + c

    d.append(t)

    d.remove(d[m])

    d.remove(d[0])

    d.sort()

    print(d,cost)


#最大二個合併

d = list(range(1,11))

print(d)

cost = 0

for i in range(len(d)-1):

    t = d[-1]+d[-2]

    c = abs(d[-1]-d[-2])

    cost = cost + c

    d.append(t)

    d.remove(d[-3])

    d.remove(d[-2])

    d.sort()

    print(d,cost)

2023年12月25日 星期一

使用遞迴控制列印次數

 def f(n):

print('i love python')

if n==1:return 

return f(n-1)


n = int(input())

f(n)

2023年12月22日 星期五

Python sys.getsizeof()

 import sys

print('bool:',sys.getsizeof(True) )

print('char:',sys.getsizeof('a') )

print('short:',sys.getsizeof(1) )

print('int:',sys.getsizeof(65537) )

print('float:',sys.getsizeof(1048577) )

print('double:',sys.getsizeof(1.1) )


bool: 28↵\r\n

char: 42↵\r\n

short: 28↵\r\n

int: 28↵\r\n

float: 28↵\r\n

double: 24↵\r\n

2023年12月21日 星期四

graph has loop ?

 #d = [[0,1],[1,2],[2,3],[3,4]] # no loop

d = [[0,1],[1,2],[2,3],[3,2]]

node = []

edge = []

for i in d:

    node.append(i[0])

    node.append(i[1])

    edge.append([i[0],i[1]])

  

node = set(node)

#edge = set(edge)

links = []

for i in node:

    t =str(i)

    for j in edge:

        if j[0]==i:

           t = t + str(j[1]) 

    links.append(t)


links1 = []

for i in links:

    t = i

    for j in edge:

        if i[-1] == str(j[0]):

            t = t + str(j[1])

    links1.append(t)

links2 = []

for i in links1:

    t = i

    for j in edge:

        if i[-1] == str(j[0]):

            t = t + str(j[1])

    links2.append(t)

    

for i in links2:

    if len(list(i))!=len(set(i)):

        print(i,':loop')

        

2023年6月14日 星期三

字數統計

d = '''

Full Transcript: NVIDIA CEO Jensen Huang's Commencement Address at National Taiwan University

Ladies and gentlemen, esteemed faculty members, distinguished guests, proud parents, and above all, the 2023 graduating class of the National Taiwan University. Today is a very special day for you, and a dream come true for your parents.

...

...
 You will endure pain and suffering needed to realize your dreams. And you will make sacrifices to dedicate yourself to a life of purpose and doing your life's work.

Class of 2023, I extend my heartfelt congratulations to each one of you.  Jiayou!

'''

d = d.replace(':',' ').replace('.',' ').replace('\'',' ').replace(',',' ')

d1= [ i for i in d.split() if i> '9' and len(i)>1]


s = set(d1)

r = []

for i in s:

    r.append( [d1.count(i),i])

r.sort()

r.reverse()

#for i in r[:100]:

#    print(i[0],':',i[1])

#

#r100 = r[0:100]

#s100 =0

#for i in r100:

#    s100 = s100 + i[0]

#p = s100/len(d1)*100

#p = int(p*100+0.5)/100

#print('會前', len(r100),'個字, 就可看懂整篇1781字文章的',p,'%')

#

#r200 = r[0:200]

#s200 =0

#for i in r200:

#    s200 = s200 + i[0]

#p = s200/len(d1)*100

#p = int(p*100+0.5)/100

#print('會前', len(r200),'個字, 就可看懂整篇1781字文章的',p,'%')

#

#r300 = r[0:300]

#s300 =0

#for i in r300:

#    s300 = s300 + i[0]

#p = s300/len(d1)*100




#p = int(p*100+0.5)/100

#print('會前', len(r300),'個字, 就可看懂整篇1781字文章的',p,'%')

for n in range(100,800,100):

    rr = r[0:n]

    s =0

    for i in rr:

        s = s + i[0]

    p = s/len(d1)*100

    p = int(p*100+0.5)/100

    print('會前', len(rr),'個字, 就可看懂整篇1781字文章的',p,'%')


#執行結果

#會前 100 個字, 就可看懂整篇1781字文章的 53.23 %

#會前 200 個字, 就可看懂整篇1781字文章的 67.66 %

#會前 300 個字, 就可看懂整篇1781字文章的 76.59 %

#會前 400 個字, 就可看懂整篇1781字文章的 82.2 %

#會前 500 個字, 就可看懂整篇1781字文章的 87.82 %

#會前 600 個字, 就可看懂整篇1781字文章的 93.43 %

#會前 700 個字, 就可看懂整篇1781字文章的 99.05 %

2023年2月24日 星期五

21世紀13日星期五

 import datetime


year = 2000

month = 1

day = 1


c = 0

date = datetime.date(year, month, day)

for i in range(200000):

    weekday = date.weekday()

    day = date.day

    month = date.month

    year = date.year

    

    if year>2099:

        break

    

    weekday_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

    if day==13 and weekday_names[weekday] == 'Friday':

        print(f"{c}: {year}/{month}/{day} is a {weekday_names[weekday]}")

        c = c + 1     

    date = date + datetime.timedelta(days=1)

2023年1月6日 星期五

矩陣轉置

 m = [[1,2],[3,4],[5,6]]

t = [[r[i] for r in m] for i in range(2)]

print(t)

2023年1月5日 星期四

python Date

 import datetime


print(datetime.date.today().strftime('%d/%m/%Y'))

mDate = datetime.date(1966,4,18)

print(mDate.strftime('%m/%d/%Y'))


mDateNextDay = mDate + datetime.timedelta(days=1)

print(mDateNextDay.strftime('%m/%d/%Y'))


mFirstBirthday = mDate.replace(year=mDate.year+60)

print(mFirstBirthday.strftime('%d/%m/%Y'))

2022年12月21日 星期三

python exercise REF

 http://kh-coding.blogspot.com/p/python-46.html

python exercise Ref

 https://buzzorange.com/techorange/2021/03/02/11-projects-for-python-beginner/

2022年12月20日 星期二

python sample

 result = [f'{x:04x}' for x in range(256) if x % 2 == 0]

print(result)


a, b = 0, 1

while a <100:

    print(a,end=', ')

    a, b = b, a+b

print()

    

a,b =240,360

while a!=b:

    if a<b: a,b = b,a

    a,b = b,a-b

print(a)

2022年4月26日 星期二

data clean

f = open('test2.txt','r',encoding='utf-8')
lines = f.readlines()
d = ''.join(lines)

d = d.replace('(',' ')
d = d.replace(')',' ')
d = d.replace(':',' ')
d = d.replace('.',' ')
d = d.replace('_',' ')
d = d.replace('\t',' ')
d = d.replace('  ',' ')
d = d.replace('  ',' ')
d = d.replace('  ',' ')

d = [ i for i in d if 'z' >= i >='A' or i==' ' ]

d = ''.join(d)
# print(d)
d = d.split(' ')
d = [i for i in d if len(i)>1]
d = set(d)
d = list(d)
d.sort
for i in d:
    print(i)
print(len(d))
   

2022年2月14日 星期一

小數位數及數字前面補零

 a = 1.25

print('%.6f'%a)

print(str(a).zfill(8))

轉2進位,反轉,轉10進位

 a = []

for i in range(15):

    # print(bin(i)[2:])

    a.append(bin(i)[2:].zfill(8))

print(a)

b = [''.join(list(i)[::-1]) for i in a]

print(b)

b = [int(str(i),2) for i in b]

print(b)

2022年2月13日 星期日

Recursive Loop?

 def ff(i,j,n):

    if i == j+1 :

        print()

        i=1

        return

    print(i,end='')

    ff(i+1,j,n)


def nn(i,j,n):

    if j==n+1:

        return

    ff(i,j,n)

    nn(i,j+1,n)

    

nn(1,1,5)

2022年2月11日 星期五

loop ..

 def loop(x):

    if x==0:
        return
    else:
        for i in range(1,x+1):
            print(i,end='')
        print()
        loop(x-1)
           
loop(5)

def strloop(x):
    if len(x)==0:
        return
    else:
        for i in range(len(x)):
            print(x[i],end='')
        print()
        strloop(x[:-1])
strloop('abcde')

def fact(n):
    if n==1:
        print(str(1)+'='+str(1))
        exit()
    else:
        s = 1
        for i in range(1,n+1):
            s*=i
            if i!=n:
                print(i,end='*')
            else:
                print(i,end='=')
        print(s)
        fact(n-1)
print(fact(5))

2021年6月2日 星期三

樸克牌模擬 python

 import random

ds = 'A23456789TJQK'
fs = 'SHDC'
r = []
for i in ds:
    for j in fs:
        r.append(j+i)

sd = {}
n = 1000000
for j in range(n):
    ud = []
    for i in range(5):
        u = random.randint(0,51)
        ud.append(r[u])
    print(j,ud,end=' ')

    sameCheck = [i[1for i in ud]
    sameCheck1 = [sameCheck.count(ifor i in sameCheck]
  
    nSame = int(sameCheck1.count(2)/2)
    nSame3 = sameCheck1.count(3)

    msg = ''

    if nSame3 ==1 : msg = 'Three of a kind'
    elif nSame ==2 : msg = 'Two Pair'
    elif nSame == 1:msg = 'One Pair'

    checkFlag = [fs.find(i[0]) for i in ud]
    checkFlag.sort()  

    if checkFlag[0] == checkFlag[1] == checkFlag[2] == checkFlag[3] == checkFlag[4]:
        msg = 'Flush'

    checkSame = [ds.find(i[1]) for i in ud]
    checkSame.sort()
    if (checkSame[0] == checkSame[1] == checkSame[2] == checkSame[3]
    or  checkSame[1] == checkSame[2] == checkSame[3] == checkSame[4]):
        msg = 'Four of a kind' 
    if (checkSame[0] == checkSame[1and checkSame[1] == checkSame[2and checkSame[3] == checkSame[4]
    or checkSame[0] == checkSame[1and checkSame[2] == checkSame[3and checkSame[3] == checkSame[4]):
        msg = 'FullHouse'  
    if checkSame[0] == checkSame[1]-1 and checkSame[1] == checkSame[2]-1  and checkSame[2] == checkSame[3]-1 and checkSame[3] == checkSame[4]-1:
        msg = 'Straight'  
    if (checkFlag[0] == checkFlag[1] == checkFlag[2] == checkFlag[3] == checkFlag[4]
       and checkSame[0] == checkSame[1]-1 and checkSame[1] == checkSame[2]-1  and checkSame[2] == checkSame[3]-1 and checkSame[3] == checkSame[4]-1):
        msg = 'Straight Flush' 
    
    print(nSame,msg)
    
    if msg in sdsd[msg]+=1
    else        : sd[msg]=1 

print(n'times :')
for k,v in sd.items():
    if k=='':print('%-20s : %d'%('No...',v))
    else:    print('%-20s : %d'%(k,v))

1000000 times : No... : 457108 Two Pair : 68882 One Pair : 460935 Four of a kind : 2114 Straight : 2852 Flush : 3894 FullHouse : 4201 Straight Flush : 14


2021年5月27日 星期四

分組累積例 python list

 s = [int(i) for i in input().split()]


start = 0

end = 0


while end<len(s):

acc =0

while s[start]*s[end]>0 or s[start]==0 and s[end]==0:

acc+=s[end]

end+=1

if end >=len(s): break

end = end -1

if acc>0: print(start+1,end+1,end-start+1,acc)

start = end+1

end = end+1

acc = 0

2021年5月26日 星期三

dict and multi key list sorting

 s = input().lower()

s =s.replace('.','').replace(',','').split()


d = {}

for i in s:

if i in d:

d[i]+=1

else :

d[i]=1

list1 = []

for k,v in d.items():

t = [k,v]

list1.append(t)


for i in range(len(list1)):

for j in range(i+1,len(list1)):

if list1[i][1]<list1[j][1]: list1[i],list1[j]=list1[j],list1[i]

elif list1[i][1]==list1[j][1] and  list1[i][0]>list1[j][0]:  list1[i],list1[j]=list1[j],list1[i]

for i in list1:

print(i[0],i[1])

2021年5月18日 星期二

Graph in Dict structure

 d ='''A -> B

    A -> C

    B -> C

    B -> D

    C -> D

    D -> C

    E -> F

    F -> C'''

e = [i.strip() for i in d.split('\n')]

v = set()

for i in e:

    for j in i:

        if j>='A':

            v.add(j)

v = list(v)

v.sort()


print(e)

print(v)


g = {}

for i in v:

    t = []

    for j in e:

        if i in j:

            for k in j:

                if k>='A' and k<='Z':

                    if k not in i:

                        t.append(k)

    g[i]=t

print(g)