簡體   English   中英

我無法弄清楚我在這里失敗了哪些測試用例

[英]I'm unable to figure out what test cases am I failing here

我需要找到字符串中出現的最大字符:az。 它有 26 個字符長,即 26 種不同的類型。

即使 output 是正確的,我仍然失敗。 我究竟做錯了什么?

這些是條件:

注意:如果有不止一種類型的相等最大值,則將考慮具有較小 ASCII 值的類型。

輸入格式 輸入的第一行包含測試用例的數量 T。

每個測試用例的第二行由一個字符串組成,表示每個字符的類型。

約束

1<= T <=10

1<= |字符串| <=100000

Output 格式

對於每個測試用例,在單獨的行中打印所需的 output。

示例測試用例 1

輸入

2

gqtrawq

fnaxtyyzz

Output

q

是的

解釋

測試用例 1:有 2 q 出現最大值,而 rest 全部單獨存在。

測試用例 2:有 2 個 y 和 2 個 z 類型。 由於最大值相同,因此Ascii值較小的類型被認為是output。 因此,y 是正確的類型。

def testcase(str1):

  ASCII_SIZE = 256

  ctr = [0] * ASCII_SIZE

  max = -1

  ch = ''

  for i in str1:

    ctr[ord(i)]+=1;


  for i in str1:

    if max < ctr[ord(i)]:

      max = ctr[ord(i)]

      ch = i

  return ch

print(testcase("gqtrawq"))

print(testcase("fnaxtyyzz"))

我通過了 output 即我得到了正確的 output 但未通過測試用例。

注意注釋:

注意:如果有不止一種類型的相等最大值,則將考慮具有較小 ASCII 值的類型。

但是使用您的代碼,您將返回字符串中出現的計數最高的字符 在平局的情況下,在比較中考慮角色本身:

for i in str1:
  if max < ctr[ord(i)] or max == ctr[ord(i)] and i < ch:
    max = ctr[ord(i)]
    ch = i

或者更短(但不一定更清晰)比較(count, char)的元組:

  if (max, i) < (ctr[ord(i)], ch):

(請注意,這是比較(old_cnt, new_char) < (new_cnt, old_chr) !)

或者,您也可以按排序順序迭代字符串中的字符:

for i in sorted(str1):
  if max < ctr[ord(i)]:
    ...

話雖如此,您可以通過直接計算字符而不是它們的順序來簡化/改進代碼(使用dict而不是list ),並使用帶有適當key ordmax function 來獲得最常見的字符。

def testcase(str1):
    ctr = {c: 0 for c in str1}
    for c in str1:
        ctr[c] += 1
    return max(sorted(set(str1)), key=ctr.get)

可以使用collections.Countermost_common ,但其中的樂趣在哪里?

output 應該是什么 - print(testcase("fanaxtyfzyz"))?

IMO output 應該是“a”,但您的程序寫的是“f”。 原因是您正在遍歷輸入字符串的字符,

for i in str1: #Iterating through the values 'f','a','n','a','x','t',...
               #first count of 'f' is considered. 
               #count of 'f' occurs first, count of 'a' not considered.
if max < ctr[ord(i)]: 

  max = ctr[ord(i)]

  ch = i

相反,您應該遍歷 ctr 的值。 或者對輸入字符串進行排序並執行相同的操作。

暫無
暫無

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

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