Accessing list from function - python

I am writing a function where a user puts in text and a word and if the word is in the list, it returns the location of the word in the list.
list = ["hello", "goodbye", "name"]
def fact(txt, my_list):
text = txt.split()
for i in range(0, len(my_list)):
for j in range(0, len(text)):
if(my_list[i] == text[i]):
return my_list[i]
value = fact("hello, my name is", "name")
print(value)
However, this only seems to return none every time. Is there any particular reason it is not working?

Example:
def f(text, search):
if search in text.split():
print('Word "{}" has been found # index: {}'.format(search, text.split().index(search)))
Output:
data = 'hello world, my name is -e'
f(data, '-e')
Word "-e" has been found # index: 5

this works fine
def getword(word, text):
text = text.replace(',', '') # remove ',' by nothing
tmp = text.split(' ')
if word in tmp:
print("word: [%s] find at index %s in this text:[ %s]" % (word, tmp.index(word), text))
return tmp.index(word)
else:
print("Did not find [%s] in [%s]" % (word, text))
return -1
word = "what"
text = "Hello, I am groot, what is your name"
index = getword(word, text)

Related

How do I return my output instead of print?

def spin_words(sentence):
adjusted_string = sentence.split()
for i in adjusted_string:
if len(i) > 5:
print(i[::-1], end = ' ')
else:
print(i, end = ' ')
The problem is asking to take a string and return the same string but, with all the five letter words or more in reversed
def spin_words(sentence):
splitted_string = sentence.split()
reversed_fives = [s[::-1] if len(s) >= 5 else s for s in splitted_string]
return " ".join(reversed_fives)

Error in anagram code: python

This function will search for anagrams in a list from a .txt file, I want to be able to check for anagrams and return all anagrams of the word that I input, and if it's not an anagram it will return the input, when I do it in the code below, it iterates through the for loop then ignores my first if statement and heads directly to my else statement. How can I fix this?
def find_in_dict():
input_word = input("Enter input string)")
sorted_word = ''.join(sorted(input_word.strip()))
a_word = ''.join((input_word.strip()))
word_file = open("filename", "r")
word_list = {}
for text in word_file:
simple_text = ''.join(sorted(text.strip()))
word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
if val == sorted_word:
alist.append(key)
return alist
else:
return "No words can be formed from:" + a_word
you are making a return statement in the if and else branch, that will break the for (because return invoked inside a function do exactly that, interrupt the execution and return the value) , so, don't do that, just ask if the word is equal, and in the end, check if there is none occurrences (empty list)
for text in word_file:
simple_text = ''.join(sorted(text.strip()))
word_list.update({text.strip(): simple_text})
alist = []
for key, val in word_list.items():
if val == sorted_word:
alist.append(key)
if alist == []: print("No words can be formed from: " + a_word)

Returning Value

def extract_info(text, price):
company_name = ['BMW','AUDI','MERCEDES','TOYOTA']
car_type = ['Saloon', 'Hatchback','Sedan']
if any(word in text for word in company_name):
for word in company_name:
matchWord = text.split()
if word in matchWord:
return (word)
elif any(word in text for word in car_type):
for word in car_type:
matchWord = text.split()
if word in matchWord:
return (word)
else:
productType = re.search('car', text)
if productType is not None:
productvalue = productType.group(0)
return (productvalue)
numDoor = re.search('[0-9]-door',text)
if numDoor is not None:
matchDoor = numDoor.group(0)
return (matchDoor)
else:
return ('No match')
I am trying to return a value but, couldn't get all of the value . Although i am getting my output while printing them.
I was using a string "A low maintenance, 5-door car that's safe"
The code is fetching if the string get any of the word or match with regex.
Because a function can only return once. So after line 18 :
return productType
it return the final return of function and it will never execute after line 18. Your code after line 19 is not executing that's why you are not getting rest of result. If you want to return a bunch of output then just append in a list or use dict to save different result then return that variable at last and use that variable data as you want.
An example :
import re
def extract_info(text, price):
final_output={}
company_name = ['BMW','AUDI','MERCEDES','TOYOTA']
car_type = ['Saloon', 'Hatchback','Sedan']
if any(word in text for word in company_name):
for word in company_name:
matchWord = text.split()
if word in matchWord:
final_output['word']=word
elif any(word in text for word in car_type):
for word in car_type:
matchWord = text.split()
if word in matchWord:
final_output['word']=word
else:
productType = re.search('car', text)
if productType is not None:
final_output['product_type']=productType.group(0)
numDoor = re.search('[0-9]-door', text)
if numDoor is not None:
matchDoor = numDoor.group(0)
final_output['matchdoor']=matchDoor
else:
final_output['matchdoor']='None'
return final_output
print(extract_info("A low maintenance, 5-door car that's safe",23))
You can replace print statements with return
if numDoor is not None:
matchDoor = numDoor.group(0)
return matchDoor
else:
return 'No match'

python censor function by codeacademy

def censor(text, word):
final_text = ''
new_text = ''
items = text.split()
for i in items:
if i == word:
new_text = "*" * len(word)
final_text.join(new_text)
else:
new_text = items
final_text.join(new_text)
return final_text
print censor("this hack is wack hack", "hack")
the above function is intended to censor the word "hack" with asterisks present in the text. Can I know where is the flaw in the above code. Thank you in advance.
This should be it.
def censor(text, word):
final_text = ''
new_text = ''
items = text.split()
for index, w in enumerate(items): #'index' is an index of an array
if w == word:
new_text = "*" * len(word)
items[index] = new_text # substituting the '*'
final_text = ' '.join(items) # the correct way how join works
return final_text
print censor("this hack is wack hack", "hack")
The other way:
text = 'this hack is wack hack'
word = 'hack'
print text.replace(word, '*' * len(word))
The way join() works in python is you execute it on a join sign (e.g. ' ', '-', ',' etc), and you provide the list inside the join(list_in_here)
Simple example:
>>>'-'.join(['1','human','is','a','one'])
'1-human-is-a-one'

I can't return a value

I'm trying to write a function that will translate the input into so-called "cow Latin." I want to return the values from the if statement but whenever I do I get a syntax error. I can print the value but I want to avoid the function returning None as well.
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
print('{0}moo'.format(cow_word), end=' ')
else:
cow_word = sentence_list[i][1:] + sentence_list[i][:1]
print('{0}oo'.format(cow_word), end=' ')
cow_latin = cow_latinify_sentence("the quick red fox")
print(cow_latin)
In short, how can I get the function to return instead of print?
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += ('{0}moo'.format(cow_word) + ' ')
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()
>>> cow_latinify_sentence('hello there i am a fish')
'ellohoo heretoo imoo ammoo amoo ishfoo'
Why not just replace the two instances of
print('{0}moo'.format(cow_word), end=' ')
with
return '{0}moo'.format(cow_word)+' '
You have to get rid of end=; you don't have to replace the newline that would otherwise follow the output of print, but if you want a space at the end of the returned string you still have to append it yourself.
You need to create a list to accumulate your results.
result = []
your two print statements in your function would need changed to result.append(XXXX). Then when you have processed the entire sentence you can
return (result)
or, to re-form it into a sentence:
return " ".join(result) + '.'
def cow_latinify_sentence(sentence):
vowels = tuple('aeiou1234567890!##$%^&*()-_=+|\\][}{?/.\',><`~"')
sentence = sentence.lower()
sentence_list = sentence.split()
result = ''
for i in range(len(sentence_list)):
cow_word = sentence_list[i][:]
if cow_word.startswith(vowels):
result += '{0}moo'.format(cow_word) + ' '
else:
result += '{0}oo'.format(sentence_list[i][1:] + sentence_list[i][:1]) + ' '
return result.strip()

Categories