codewars算法題(3)

第三題:

問題:You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.

Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

自己代碼:

def likes(names):
    if(len(names)==0):
        return "no one likes this"
    elif(len(names)==1):
        return names[0]+" likes this"
    elif(len(names)==2):
        return names[0]+" and "+names[1]+" like this"
    elif(len(names)==3):
        return names[0]+", "+names[1]+" and "+names[2]+" like this"
    else:
        return names[0]+", "+names[1]+" and "+str(len(names)-2)+" others like this"

評分較高代碼:

  1. def likes(names):  
  2.     n = len(names)  
  3.     return {  
  4.         0'no one likes this',  
  5.         1'{} likes this',   
  6.         2'{} and {} like this',   
  7.         3'{}, {} and {} like this',   
  8.         4'{}, {} and {others} others like this'  
  9.     }[min(4, n)].format(*names[:3], others=n-2
鵝鵝鵝~~~~~·這就是差距啊

第四題:

問題:

Accumul.accum("abcd"); // "A-Bb-Ccc-Dddd"
Accumul.accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
Accumul.accum("cwAt"); // "C-Ww-Aaa-Tttt"
The parameter of accum is a string which includes only letters from a..z and A..Z.

評分較高代碼:
(1):
      
(2):
      
(3):
      
        其中enumeratede 用法(打開鏈接有簡單介紹)
        其中title()方法返回“標題化”字符串,就是說所有單詞都是以大寫開始,其餘字母均爲小寫
第五題:(從奇中找偶,從偶中找奇)
問題:You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns N.

For example:

[2, 4, 0, 100, 4, 11, 2602, 36]

Should return: 11

[160, 3, 1719, 19, 11, 13, -21]

Should return: 160

問題陳述:目的是一個列表中異類,即列表中大多數爲偶數,則返回奇數,否則反之
代碼實現:
 (1)      
        
(2)
       
第六題:(字符串中是否有重複字符)

問題:An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.

is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
代碼實現:
(1)   
     
(2)
     
set()函數,set中參數的值是不能重複的例如:set(“hello”),結果爲‘h’‘e’‘l’‘o’
具體的set()函數介紹可看:博客





201707242237持續更新~~~~








發佈了30 篇原創文章 · 獲贊 69 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章