最大數字的函式
阿新 • • 發佈:2018-11-05
編寫一個能將給定非負整數列表中的數字排列成最大數字的函式。例如,給定[50,2,1,9],最大數字為95021
執行環境: python2.7.6
執行: ./test.py [50,2,1,9]
test.py:
#! /usr/bin/python # -*- coding:utf-8 -*- ''' 編寫一個能將給定非負整數列表中的數字排列成最大數字的函式。例如,給定[50,2,1,9],最大數字為95021 test.py ''' import sys def totalbit(value): if value > 0 : #print value value = value /10 if value == 0: return 1; return totalbit(value)+1 elif value == 0 : return 1 def hbit(value): if value > 0 : #print value valuetemp=value; value = value /10 if value == 0: return valuetemp else: return hbit(value) def maxvalue(data): mv=0; listtemp=[] listm=[] print("lista = {0}".format(data)); for a in data[1:-1].split(","): print a listtemp.append(int(a)) print "---------------------" for b in listtemp: print "================" print b print "\n" print totalbit(b) print hbit(b) listm.append(hbit(b)); print "************************" for i in range(len(listtemp)): print i for j in range(i+1,len(listtemp)): if listm[i] > listm[j]: temp = listm[i] listm[i] = listm[j] listm[j]=temp temp2 = listtemp[i] listtemp[i]=listtemp[j] listtemp[j]=temp2 print "************************" for i in range(len(listtemp)): print listtemp[i],listm[i] if mv == 0: mv = listtemp[i] else: mv = 10**(totalbit(mv)) * listtemp[i] + mv return mv; if __name__ == '__main__': print("argc = {0}".format(len(sys.argv))) print("argv[1] ={0}".format(sys.argv[1])) mv = maxvalue(sys.argv[1]) print("{0} ----> max = {1}".format(sys.argv[1],mv));
執行環境:3.4.3
執行命令: python3 test.py [50,2,1,9]
test.py
#! /usr/bin/python3 # -*- coding:utf-8 -*- """ #編寫一個能將給定非負整數列表中的數字排列成最大數字的函式。例如,給定[50,2,1,9],最大數字為95021 #test.py #python 3.4.3 """ import sys def totalbit(value): if value > 0 : #print value value = value //10 if value == 0: return 1; return totalbit(value)+1 elif value == 0 : return 1 def hbit(value): if value > 0 : #print value valuetemp=value; value = value //10 if value == 0: return valuetemp else: return hbit(value) def maxvalue(data): mv=0; listtemp=[] listm=[] print("lista = {0}".format(data)); for a in data[1:-1].split(","): print (a) listtemp.append(int(a)) print("---------------------") for b in listtemp: print("================") print(b) print("{0},{1}".format(totalbit(b),hbit(b))) listm.append(hbit(b)); print("************************") for i in range(len(listtemp)): print (i) for j in range(i+1,len(listtemp)): if listm[i] > listm[j]: temp = listm[i] listm[i] = listm[j] listm[j]=temp temp2 = listtemp[i] listtemp[i]=listtemp[j] listtemp[j]=temp2 print("************************") for i in range(len(listtemp)): print (listtemp[i],listm[i]) if mv == 0: mv = listtemp[i] else: mv = 10**(totalbit(mv)) * listtemp[i] + mv return mv; if __name__ == '__main__': print("argc = {0}".format(len(sys.argv))) print("argv[1] ={0}".format(sys.argv[1])) mv = maxvalue(sys.argv[1]) print("{0} ----> max = {1}".format(sys.argv[1],mv));