2017-01-08 6 views
4

2つのバージョンは、反対の答えを返しますが、常に1つは間違っています。私はどこが間違っているのか分からない。私は一連の他のオプションを試しましたが、これが最も近いと思われます。 EDIT:リストは[]である場合、それに応じて文字列を返す識別、要素がリストにない場合に識別し、リスト内の要素を識別:ループ内Python Loop Iteration問題

目標される必要があります。

def search_for_string(a_list, search_term): 
    i=0 
    for search_term in a_list: 
     i += 1 
     if a_list[i] == search_term: 
      return 'string found!' 
     elif a_list[i] != search_term: 
      return 'string not found2' 
    if len(a_list) == 0: 
     return 'string not found' 

apple = search_for_string(['a', 'b', 'c'], 'd') 
print(apple) 


def search_for_string(a_list, search_term): 
    i=0 
    for search_term in a_list: 
     if a_list[i] == search_term: 
      return 'string found!' 
     elif a_list[i] != search_term: 
      return 'string not found2' 
     i += 1 
    if len(a_list) == 0: 
     return 'string not found' 

apple = search_for_string(['a', 'b', 'c'], 'd') 
print(apple) 

他のテスト:

apple = search_for_string(['a', 'b', 'c'], 'b') 
apple = search_for_string([], 'b') 
+2

まず、変数search_termの値を上書きしています。たとえば、 'd'として渡していますが、forループが同じ変数名を使用するため、上書きされます。何が起きているのかを見るには、forループの中にsearch_termの値を表示してみてください。 (つまり、forループの最初の行の下に 'print(search_term)'を追加してください)。これはデバッグに役立ちます。 –

+0

あなたは何を意味しているのか分かりませんが、私は何をするべきか分かりません。私は気をつけています。 – Megan

+0

'enumerate() 'を調べるといいでしょう。 – boardrider

答えて

8

Pythonはこの種のもののためにあなたの人生は、超簡単です:

def search_for_string(a_list, search_term): 
    if search_term in a_list: 
     return 'string found!' 
    return 'string not found' 
2

短い答えは!=のリターンはあなたはそれがないと思う何とリストは0から始まるインデックス1インデックスされていないことをしないということです。コードは実際にあなたが考えるよりはるかに簡単です:

基本的に
def search_for_string(haystack, needle): 
    if not haystack: # check for empty list 
     return 'List was empty!' 
    for x in haystack: 
     if needle == x: 
      return 'String found!' 
    return 'String not found!' 

お経と少なくとも一度は各要素をチェックした場合、文字列が見つからなかった場合、あなただけ知っています。しかし、文字列が見つかった場合は、文字列が見つかったかどうかを知ることができます。


あなたのコードの問題を説明する:(1)それは、リストの最初の要素をスキップし、(2)それは文字列を返すが見つからないため、このバージョンでは動作しません

  1. をヨーヨーを通じてステップでは、この手順を見てみましょうさらに少し説明すると

    def search_for_string(a_list, search_term): 
        i=0 
        for search_term in a_list: 
         i += 1 
         if a_list[i] == search_term: # whoops this comparison checks for succeeding elements! 
          return 'string found!' 
         elif a_list[i] != search_term: # whoops this part returns even before all succeeding elements are checked. 
          return 'string not found2' 
        if len(a_list) == 0: 
         return 'string not found' 
    
    apple = search_for_string(['a', 'b', 'c'], 'd') 
    # In the list ['a', 'b', 'c'] 
    # element [0] = 'a' 
    # element [1] = 'b' 
    # element [2] = 'c' 
    print(apple) 
    

:/最初の要素だけをチェックした後に見つかりましたあなたの2番目のバージョンには同じ問題(1)(2)がありますが、最初の要素がチェックされていないという問題は回避されます。

+1

'' 'if needle == haystack'''' '' 'if needle == x'''? – wwii

+0

これをキャッチしていただきありがとうございます。 – 2ps

+0

はい、これは動作します。申し訳ありませんループ内でこれをしようとしているのを忘れてしまいました。 – Megan

1

search_for_string機能にはさまざまな問題があります。

主な問題は、変数search_termの値を上書きすることです。間違った出力を引き起こしている他の問題もあります。

ここでは、機能のより簡単なバージョンですが、すべての要件を満たしています。

def search_for_string(a_list, search_item): 
    if(len(a_list) == 0): 
     return 'List is empty' 
    else: 
    for search_term in a_list: 
     if search_term == search_item: 
      return 'string found!' 
    return 'string not found' 
3

あなたのコードで間違ったおよび非Python的がいくつかあります:

def search_for_string2(a_list, search_term): 
    i=0 # <----- Not Pythonic! If you want to get index we use enumerate(a_list) 
    for search_term in a_list: # <--- search_term passed to function is lost and gets overwritten by elements in a_list. 
     i += 1 # <--- Not Pythonic in this context 
     if a_list[i] == search_term: #<--- a_list[index+1] == a_list[index]. True if consecutive elements are same else False! 
      return 'string found!' #<--- No WRONG!, You didn't find the string, Consecutive elements are same! 
     elif a_list[i] != search_term: 
      return 'string not found2' #<-- Consecutive elements are not same! 
    if len(a_list) == 0: 
     return 'string not found' 

よりますあなたが定義した目標にそれを実装することができます:

def search_for_string(alist, search_term): 
    if not alist: 
     return "List is empty" 
    if search_term in alist: 
     return "First occurence of string Found at index position: " + str(alist.index(search_term)) 
    else: 
     return "String not found" 


print(search_for_string(['a', 'b', 'c'], 'd')) 
print(search_for_string(['a', 'b', 'c'], 'b')) 
print(search_for_string([], 'b')) 

出力:

String not found 
First occurence of string Found at index position: 1 
List is empty 
1

あなたはあなたの中のコードでかなりの数のエラーを持っています。重要なものもあれば、そうでないものもあります。あなたは、関数の引数として変数search_termを受けている

  • が、あなたは、あなたのforループでそれを使用することによって、それの値を上書きする:私はそれらに対処しようとするでしょう。
  • a_listを値で反復していますが、ループ変数iを使用してインデックスを反復しようとします。これをしないでください。あなたはすでに価値によって反復しています。両方を行う必要はありません。
  • 機能の末尾a_listが空であるかどうかをテストしようとしています。最初はやりなさい。さらに、if文を削除して、関数の最後に戻ってください。 a_listが空の場合、forループは実行されません。今

、ここで私はあなたの関数を書き換えたい方法です:あなたのコードの場合

>>> def search_for_string(lst, key): 
    # only iterate by value. 
     for string in lst: 
      # we only need to test once 
      # if `key` is equal to the 
      # current string we are on. 
      if string == key: 
       return 'string found' 
     # no need to test if the list 
     # is empty. The for loop will 
     # never be run if it is, and 
     # this return statement will 
     # execute. 
     return 'string not found' 

>>> search_for_string(['a', 'b', 'c'], 'd') 
'string not found' 
>>> search_for_string(['a', 'b', 'c'], 'b') 
'string found' 
>>> search_for_string([], 'b') 
'string not found' 
>>> 
1

、あなたが適切に探していないことに注意してください。 search_termを渡しますが、for x in yの変数は、xをyの次の項目の値と等しくなるように設定します。あなたがfor x in [1, 2, 3]を持っていれば、最初にx = 1などを設定します。したがって、最初の関数は 'a' == 'b'であるかどうかをチェックし、2番目の関数は 'a' = 'a'、それはありますが、どちらもあなたが探しているものではありません!

項目がリストにある場合は見つけるための最善の方法は、xがリストにであるかどうか、これは、TrueまたはFalseを返します

x in list 

です! (変数 'list'は使用しないでください。組み込み関数を隠しているので悪いことです)。

だから、これを行うために、よりPython的な方法は、

def search_for_string(a_list, search_term): 
    if search_term in a_list: 
     return 'string found!' 
    elif not a_list: # realistically you'd put this before here but I'm trying to mirror your code--why might you put this earlier? Because it's less costly than searching a list. 
     return 'empty list!' 
    else: 
     return 'string not found!' 

だろう。また、リストが空の場合、我々はどのようにチェックしている、bool([]) Falseを返しますことに注意してください。

これを行うには、インデックス値を使用する必要はありませんが、余分な不要な作業を頻繁に行う必要があります。

def search_for_string(a_list, search_term): 
    for index, item in enumerate(a_list): 
     if a_list[index] == search_term: 
      return 'string found!' 
      # what do you think the value of 'item' is here? it's equal to a_list[index]! 
     elif len(a_list) == 0: # again, you'd put this earlier--why make your computer do the work? it doesn't have to. Also, you could just do elif not a_list 
      return 'string not found' 
     else: 
      continue 
    return 'string not found2' 
1

あなたのコードに関連する問題のほとんどは、ここでは、前の回答で覆われており、@Stephenラウフによって与えられた答えは、あなたの問題に最もPython的なアプローチをまとめています。

他のものがすべて正しかったとしても、あなたのコードがあなたのことをしないようにするもう1つのことがあります。

関数内のreturnを有効にすると、その関数は効果的に終了します。

ループアプローチを使用すると効果的です。a_listの最初の値をチェックし、検索条件を満たす場合は「Found」を返し、最初の値が「No」の場合は「Not found」を返します。値はではありませんでした。は検索条件に一致してから機能を終了しました。

基本的に、最初の値を超えてチェックすることはありません。

1

まず、最初のメソッドと2番目のメソッドの違いは、if文が実行される前と後で増分しています。最初にインクリメントすると、ループはリストの最初の要素の値を見つけられません。 あなたは増分としてiを使用していますが、Pythonでは必要ありません。要素がリストに含まれているかどうかを調べるだけで見つけることができます。

def search_for_string(a_list, search_term): 

    #if a_list is empty, return False 
    if len(a_list) == 0: 
      return False 
    #if search_term has an element in a_list return the string 
    if search_term in a_list: 
      return "string found" 

    return "string not found"