How to search for a variable in a list of strings

250
April 29, 2017, at 03:07 AM

I have very basic python knowledge. This is my code so far: when i run this code the error UnboundLocalError: local variable 'response' referenced before assignment on line 7 displays. I am trying to create a function that compares the response input to two lists and if that input is found true or false is assigned to response. I also need to assign response, which should be true or false to another list of answers. (true or false will be assigned values and the total of the list of answers will be calculated to match a final list calculation).

response = [str(input("Would you rather eat an apple or an orange? Answer apple or orange."))]
list1 =[str("apple"), str("Apple"), str("APPLE")]
lsit3 = [str("an orange"), str("Orange"), str("orange"), str("an Orange"), str("ORANGE")]
def listCompare():
 for list1[0] in list1:
    for response[0] in response:
      if response[0] == list1[0]:
        response = true
      else:
        for list3[0] in list3:
          for response[0] in response:
            if response[0] == list3[0]:
              response = false
listCompare()
Answer 1

You are complicating things a lot here, but that is understandable if you are new to programming or python.

To put you on the right track, this is a better way to attack the problem:

valid_responses = ['a', 'b']
response = input("chose a or b: ").lower().strip()
if response in valid_responses:
    print("Valid response:", response)
else:
    print("Invalid response:", response)

Look up any function you don't understand here.

String declarations can also just be in single or double quotes:

my_strings = ['orange', "apple"]

Also to make global variables assignable inside a function you need to use the global keyword.

my_global = "hello"
def my_fuction():
    global my_global
    # Do stuff with my_global

For loops should assign to new local variables:

options = ['a', 'b', 'c']
for opt in options:
    print(opt)
Answer 2

Instead of enumerating a list of exact possible answers, you could instead match against patterns of possible answers. Here is one way to do that, case insensitively:

import re
known_fruits = ['apple', 'orange']
response = str(input("What would you like to eat? (Answer " + ' or '.join(known_fruits) + '): '))
def listCompare():
    for fruit in known_fruits:
        pattern = '^(?:an\s)?\s*' + fruit + '\s*$'
        if re.search(pattern,response,re.IGNORECASE):
            return True
if listCompare():
    print("Enjoy it!")
else:
    print("'%s' is an invalid choice" % response)

This would match apple, Apple, or even ApPle. It would also match 'an apple'. However, it would not match pineapple.

Here is the same code, with the regular expression broken down:

import re
known_fruits = ['apple', 'orange']
print("What would you like to eat?")
response = str(input("(Answer " + ' or '.join(known_fruits) + '): '))
# Change to lowercase and remove leading/trailing whitespace
response = response.lower().strip()
def listCompare():
    for fruit in known_fruits:
        pattern = (
                  '^'     + # Beginning of string
                  '('     + # Start of group
                    'an'  + #    word "an"
                    '\s'  + #    single space character
                  ')'     + # End of group
                  '?'     + # Make group optional
                  '\s*'   + # Zero or more space characters
                  fruit   + # Word inside "fruit" variable
                  '\s*'   + # Zero or more space characters
                  '$'       # End of the string
                  )
        if re.search(pattern,response):
            return True
if listCompare():
    print("Enjoy it!")
else:
    print("'%s' is an invalid choice" % response)
READ ALSO
Trying to wrap my head around python property decorator [duplicate]

Trying to wrap my head around python property decorator [duplicate]

This question already has an answer here:

236
How to recognize Chinese or English name using python [on hold]

How to recognize Chinese or English name using python [on hold]

Given a bunch of names, how can we find out which are Chinese names and which are English names? For the Chinese names, I build a list of the Chinese last names to find out the Chinese namesFor example, Bruce Lee, Lee is a Chinese last name, so we regard...

466
Elasticsearch: Data too large, data for [_uid] would be larger than limit of [1267571097/1.1gb]]

Elasticsearch: Data too large, data for [_uid] would be larger than limit of [1267571097/1.1gb]]

I'm trying to query elasticsearch to retrieve some document that got the keyword #test in their documentsThe all_hateful_ids is a list of id

555