第18題:(printer_error)
問題:
In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a
to m
.
The colors used by the printer are recorded in a control string. For example a "good" control string would be aaabbbbhaijjjm
meaning
that the printer used three times color a, four times color b, one time color h then one time color a...
Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm
.
You have to write a function printer_error
which given a
string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler
expression.
The string has a length greater or equal to one and contains only letters from a
to z
.
#Examples:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"
s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"
問題描述:其實說簡單了就是找出一個字符串中不在‘abcdefghijklm’中的個數,並返回其所佔的比例
代碼實現:
def printer_error(s): c=0 for i in range(0,len(s)): if s[i] not in 'abcdefghijklm': c+=1 return str(c)+"/"+str(len(s))評分較高代碼:
(1)
from re import sub def printer_error(s): return "{}/{}".format(len(sub("[a-m]",'',s)),len(s)
在此簡單解釋一下sub()函數,sub()函數中第一個參數是要替換掉的字符,第二個參數是用什麼替換,第三個參數是
替換哪個字符串的字符,該例中實現的是將s字符串中的[a-m]替換成空。具體使用方法可參見博客
format()函數實現格式化將format中的參數按前面”{}/{}”格式輸出。
(2)
def printer_error(s): return "%s/%s" % (len(s.translate(None, "abcdefghijklm")), len(s))該方法中使用了translate()函數,將s字符串中的“abcdefghijklm”刪除,與方法一異曲同工
(3)
def printer_error(s): import re return str(len(re.findall('[n-z]', s))) + "/" + str(len(s))該方法用了findall()函數,方法詳解見博客
(4)
def printer_error(s): s1 = len([ x for x in s if ord(x) > ord('m')]) return str(s1) +'/' + str(len(s))第19題(切巧克力問題)
問題:
Description:
Your task is to split the chocolate bar of given dimension n
x m
into small squares. Each square is of size 1x1 and unbreakable. Implement a
function that will return minimum number of breaks needed.
For example if you are given a chocolate bar of size 2
x 1
you can split it to single squares in just one break, but for size 3
x 1
you must do two breaks.
If input data is invalid you should return 0 (as in no breaks are needed if we do not have any chocolate to split). Input will always be a non-negative integer.
def breakChocolate(n, m): return ((n * m - 1) if n * m > 1 else 0)
評分較高代碼:
def breakChocolate(n, m): return max(n * m - 1, 0)這一題很簡單不做過多解釋
201707261335 持續更新中~~~