簡體   English   中英

為什么我的 Python 測試用例在這個編碼挑戰中失敗了?

[英]Why is my Python test case failing in this coding challenge?

這是問題所在:

給定一個字符串,返回長度為 2 的子字符串在字符串中出現的次數以及字符串的最后 2 個字符的計數,因此“hixxxhi”產生 1(我們不會計算結束子字符串)。

last2('hixxhi') → 1 last2('xaxxaxaxx') → 1 last2('axxxaaxx') → 2

我的解決方案::

def last2(str):
  excl_last2 = str[:-2];
  list_excl_last2=[];

  for i in range(len(excl_last2)-1):
    list_excl_last2.append(excl_last2[i:i+2]);
  count = 0;
  for i in list_excl_last2:
    if str[-2:] == i:
      count = count + 1;
  return count;

它通過所有測試用例,除了 if str = 'xxxx' 。 我的程序返回 1。預期的輸出是 2。為什么會發生這種情況?

在掃描匹配項之前,您要從字符串中刪除最后兩個字符。 所以在那個測試用例中excl_last2 = 'xx' ,那里只有一個匹配項。

您應該只刪除最后一個字符,而不是最后兩個字符。

順便說一句,您不應該使用標准函數的名稱作為變量名稱。 strcount是標准的內置函數

您可以在第一個循環中進行計數,而不是構建子字符串列表。

def last2(string):
  excl_last1 = string[:-1];
  last2 = string[-2:]
  ct = 0
  for i in range(len(excl_last2)-1):
    if excl_last2[i:i+2] == last2:
      ct += 1
  return ct  
def last2(str):
  last2chars = str[len(str)-2:];
  count=0;
  for i in range(len(str)-2):
    if str[i:i+2]==last2chars:
      count = count + 1;  
  return count;

上面的代碼通過了所有的測試用例。 感謝 Barmar 對失敗的測試用例的合乎邏輯的解釋; 根據我的建議修改了它,現在它似乎通過了所有測試用例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM