最近刷了一些Codewars上的題目,整理如下,與大家分享一哈!
1.Roman Numerals Encoder
Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Example:
solution(1000) # should return 'M'
Help:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Remember that there can't be more than 3 identical symbols in a row.
題目大概意思說一下:給定一個正數n,把這個數用羅馬數字表示出來。
思路分析:讀完英文之後的你,一開始必定一頭霧水。明白題目意思之後,首先的疑問是,這個轉化規則怎麼整呢?心裏暗自問候一下出題者本人,然後繼續陷入沉思...
爲了弄明白這個規則,咱們看題,題目說羅馬數字一列是不會有三個重複的數字的,開始舉例。
1-I
2-II
3-III
4-IV
發現沒有,還真的是這樣,再繼續舉例
5-V
6-VI
7-VII
8-VIII
9-IX
哎?爲什麼這樣表示呢?再看一下10-X,猜測這類數字應該是9=10-1,然後表示9的時候,把10和1倒過來表示。爲了驗證猜測,我們看900-CM,90-XC,猜想正確,表示規律的謎底已經被我們解開。
那麼,如何用程序來進行這種轉換呢?我們還是老思路,由特殊到一般:
比如說我們的數字是15,怎麼才能把他轉換到XV呢?15=10+5,由此我們想到可以用減去數字的方式獲取15的數字組成。15-10=5,所以15代表的羅馬數字一定有X,5-5=0,完結,所以15=XV。可以通過dictionary來設置數字和字符的對應關係。我們要注意一點,一定要從最大的數字開始減,比如15不能先15-5=10,那麼前面開頭的數字就是V,明顯不對,因此我們要對dictionary中的值進行排序。我們用sorted函數進行排序。
def solution(n):
# TODO convert int to roman string
finalStr=""
translationRule={1000:'M',900:'CM',500:'D',400:'CD',100:'C',90:'XC',50:'L',40:'XL',10:'X',9:'IX',5:'V',4:'IV',1:'I'}
for x in sorted(translationRule.keys(),reverse=True):#reverse=true代表降序排列
while n>=x:
finalStr+=translationRule[x]
n-=x
return finalStr
代碼比較簡單,就不在詳細說明了。
2.Sum of Digits / Digital Root
In this kata, you must create a digital root
function.
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
Here's how it works:
digital_root(16)
=> 1 + 6
=> 7
digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6
digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6
digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2
其實題意很明顯了,例子已經告訴我們函數的功能是什麼
思路:把給定整數的每一個位數單獨拆分出來進行累加,然後判斷一下是否已經爲個位數。思路很簡單,但是如果對python語法不熟悉的話,也會被繞進去。
注意:
6/10=0.6
6//10=0
在python中就是有這樣的語法規則,第一種思路代碼如下:
def digital_root(n):
while n//10!=0 :
temp=n;
n=0;
while temp!=0 :
n=n+temp%10
temp=temp//10
return n
第二種思路:
運用python內置函數sum和map,代碼如下:
def digital_root(n):
# ...
while n>9:
n=sum(map(int,str(n)))#sum會對其中的可迭代對象,如:列表、元組、集合進行求和.
return n
#map函數把大於9的整數全部變成單個整數,並用迭代器的形式進行存儲