Break from for loop - python

Here is my code:
def detLoser(frag, a):
word = frag + a
if word in wordlist:
lost = True
else:
for words in wordlist:
if words[:len(word) == word:
return #I want this to break out.
else:
lost = True
Where I have a return, I've tried putting in both return and break and both give me errors. Both give me the following error: SyntaxError: invalid syntax. Any Ideas? What is the best way to handle this?

You've omitted the ] from the list slice. But what is the code trying to achieve, anyway?
foo[ : len( foo ) ] == foo
always!
I assume this isn't the complete code -- if so, where is wordlist defined? (is it a list? -- it's much faster to test containment for a set.)

def detLoser(frag, a):
word = frag + a
if word in wordlist:
lost = True
else:
for words in wordlist:
if word.startswith(words):
return #I want this to break out.
else:
lost = True
you can probably rewrite the for loop using any or all eg. ( you should use a set instead of a list for wordlist though)
def detLoser(frag, a):
word = frag + a
return word in wordlist or any(w.startswith(word) for w in wordlist)

Related

Where is the fault in this function?

with open("german.txt") as f:
words = f.read().split()
for word in words:
color = word.lower().replace("o", "0").replace("i", "1").replace("s", "5").replace("t", "7")
if len(word) == 3 or len(word) == 6:
ok = True
for c in color:
if c not in "abcdef0123456789":
ok = False
break
if ok:
print(word, "#" + color)
This program works, but why doesn't it work anymore when I add a function structure to it?
with open("german.txt") as f:
words = f.read().split()
def replace_letters_with_numbers(word):
color = word.lower().replace("o", "0").replace("i", "1").replace("s", "5").replace("t", "7")
def is_valid_color(word):
if len(word) == 3 or len(word) == 6:
ok = True
for c in color:
if c not in "abcdef0123456789":
ok = False
break
if ok:
print(word, "#" + color)
for word in words:
replace_letters_with_numbers(word)
is_valid_color(word)
Thanks in advance!
There are a few different issues.
Scoping
Return values
With your top-down approach, all the variables are defined.
Your functional approach straight up just not doing anything. For example, the replace_letters_with_number function is just assigning the new word into a local variable and returning nothing. Basically this function does nothing. One way to solve this is to return the updated word.
def replace_letters_with_numbers(word):
return word.lower().replace("o", "0").replace("i", "1").replace("s", "5").replace("t", "7")
Another issue is that when you run the is_valid_color the variable color technically does not exist. If we assume that the word being passed intno this function has already been replaced we can change the variable color to word.
With these approaches we could change how the for loop is executed, by assigning a variable color when we call replace_letters_with_number. Resulting in:
for word in words:
color = replace_letters_with_numbers(word)
is_valid_color(color)
There are other improvements that could be made; however, the main issue was that the variable color was not defined.
What I find wrong with your code:
your fist function is correct but is does not return anything. this means you cannot use the word resulting from this function in the subsequent functions. (so add )
return color
in your second function you must pass the returned value instead of word. Because word will still be in this case the raw word you read.
Also if you prefer and based on my observation I suggest splitting the functions into 3 for clarity as below. And from you code this is my understanding (correct if i got this wrong)
read a series of words and replace specific letters with numbers
filter only words of length 3 and 6
filter words from 2 with characters that are within the alpha-numeric characters defined by you.
The below code does this exactly.
def color_word(word):
color = word.lower().replace("o", "0").replace("i", "1").replace("s", "5").replace("t", "7")
return color
def word_length_is_3_and_6(word):
ok = False
if len(word) == 3 or len(word) == 6:
ok = True
print(f'{word} has {len(word)} letters \n resulting color from word : {color_word(word)}')
return ok
def check_alpha_numeric_state(word):
ok=True
for each_char in word:
if each_char not in "abcdef0123456789":
ok = False
print('all letters in word are not alphanumeric - [abcdef0123456789]')
break
else:
print(word, "#" + color_word(word))
if __name__ == '__main__':
words = ['happil', 'nos', 'Trusts' 'shon']
for each_word in words:
colorword = color_word(each_word) #returns the word with replaced letters and numbers
word_length = word_length_is_3_and_6(each_word) #boolean
if word_length == True:
check_alpha_numeric_state(colorword)

Why is there a memory error showing when I try to run this code?

So I'm having to write a function that does this:
Write the function called remove_all_from_string that takes two strings and returns a copy of
the first string with all instances of the second string removed. You can assume that the
second string is only one letter, like "a". For example remove_all_from_string("house", "h")
would output "ouse" or remove_all_from_string("haus", "h") would output "aus".
It has to have:
A function definition with parameters.
A while loop.
The find method.
Slicing and the + operator.
A return statement.
def remove_all_from_string(word, letter):
while letter in word:
x = word.find(letter)
if x == -1:
continue
else:
new = list(word)
new[x] = ""
word = str(word[:x]) + word.join(new)
return word
print(remove_all_from_string("Mississippi", "i"))
Every time I try to run this, Python displays an Error Message:
Traceback (most recent call last):
File "scratchpad.py", line 22, in <module>
print(remove_all_from_string("Mississippi", "i"))
File "scratchpad.py", line 19, in remove_all_from_string
word = str(word[:x]) + word.join(new)
MemoryError
Could anyone help with this? Thank you for any answers!
Your code getting trapped in a forever loop because of word.join(new) that you are adding word again and again ant word grows to infinity.
The way you can fix your code:
def remove_all_from_string(word, letter):
while letter in word:
x = word.find(letter)
if x == -1:
continue
else:
new = list(word)
new[x] = ""
word = "".join(new[:x] + new[x+1:])
return word
print(remove_all_from_string("Mississippi", "i"))
Better way to implement this function:
def remove_all_from_string(word, letter):
return word.replace(letter, "")
Simplify the while loop's logic:
There's already an answer with the 'best' way to solve the problem. In general, if I think I need a while loop I'm normally wrong, but if they're a requirement they're a requirement I guess.
def remove_all_from_string_converted(word: str, letter: str) -> str:
while letter in word:
index: int = word.find(letter)
word = word[:index] + word[index+1:] # 'join' isn't necessary unless it's also required by a rule
return word
print(remove_all_from_string_converted("Mississippi", "i"))
Output: Msssspp
You are accumulating copies of the variable "word" into itself, which results in exponential growth of the data in the variable, resulting in the computer running out of RAM. Given the task description this is a bug.
As it seems you may be new to programming, I suggest this strategy for helping yourself: print the values of all your variables (and add new variables for important intermediate results) so you can see what your program is actually doing. Once you understand what the program is doing, you can begin to fix it.
def remove_all_from_string(word, letter):
debug_loop_count = 0
while letter in word:
debug_loop_count += 1
if debug_loop_count > 2: # (change this to number control the # of loops you print)
print(f"breaking loop because debug_loop_count exceeded")
break
print(f"--- begin loop iteration #{debug_loop_count}, word: '{word}'")
x = word.find(letter)
if x == -1:
print(f"--- end loop iteration #{debug_loop_count} x={x} (continue)")
continue
else:
new = list(word)
print(f"variable new is: '{new}' x={x}")
new[x] = ""
print(f"variable new is updated to: '{new}' x={x}")
str1 = str(word[:x])
str2 = word.join(new)
print(f"variable str1 is: '{str1}'")
print(f"variable str2 is: '{str2}'")
word = str1 + str2
print(f"variable word now contains: '{word}'")
print(f"--- end iteration loop #{debug_loop_count}")
print(f"!!! end of function, word = {word}")
return word
print(remove_all_from_string("Mississippi", "i"))

python check if anagram on a string

hello i have made a function that checks if two strings are a anagram but, i don't know how to implement it on a full length sentence, e.g:
'voLa' 'alVo' -----> these words are an anagram and it returns True
but what im trying to do is on an egg like this:
'hello vola alvo my name is ...' , -----> 'hello my name is ...'
And i dont know how to do it, can anyone help me?
def anagram(a, b):
if len(a)==len(b) and sorted(a)==sorted(b):
return True
else:
return False
To filter occurrences of anagrams, you could place the original words in a dictionary where the key is formed of the sorted letters. Any subsequent word would find the anagram by looking up its sorted letters in the dictionary. To isolate words, a regular expression would be best because you can use the sub() function to replace words with the result of a function.
import re
def stripAnagram(match):
word = match.group().lower()
key = "".join(sorted(word))
if anagrams.setdefault(key,word) != word:
return ''
return match.group()
s = 'data tada base has wrong data'
anagrams = dict()
s = re.sub(r'\w+',stripAnagram,s)
print(s)
data base has wrong data
If the anagram appears next to the original word, you can modify a little your function to detect anagrams and do:
def isAnagram(a, b):
if sorted(a.lower())==sorted(b.lower()) :
return True
else:
return False
#this is the same as the above
# def isAnagram(a, b):
# return sorted(a.lower())==sorted(b.lower())
then remove the anagrams:
def removeAnagrams(phrase):
words = phrase.split(' ')
newWords = []
oldWord = ''
for word in words:
if not isAnagram(word, oldWord):
newWords.append(word)
oldWord = word
print(newWords)
newPhrase = ' '.join(newWords)
return newPhrase
and test:
phrase = "There was a beautifyll day. The saw was sharped"
print(removeAnagrams(phrase))
#There was a beautifyll day. The saw sharped

Python - Dictionary function only one entry for dictionary

Sorry if this is a silly question but I am new to python. I have a piece of code that was opening a text reading it, creating a list of words, then from that list create a dictionary of each word with a count of how many times it appears in the list of words. This code was working fine and was printing out the dictionary fine however when i put it in a function and called the function it returns the dictionary but only with one entry. Any ideas why, any help is much appreciated.
def createDict():
wordlist = []
with open('superman.txt','r', encoding="utf8") as superman:
for line in superman:
for word in line.split():
wordlist.append(word)
#print(word)
table = str.maketrans("!#$%&()*+, ./:;<=>?#[\]^_`{|}~0123456789'“”-''—", 47*' ' )
lenght = len(wordlist)
i = 0
while i < lenght:
wordlist[i] = wordlist[i].translate(table)
wordlist[i] = wordlist[i].lower()
wordlist[i] = wordlist[i].strip()
i += 1
wordlist = list(filter(str.strip, wordlist))
word_dict = {}
for item in wordlist:
if item in word_dict.keys():
word_dict[item] += 1
else:
word_dict[item] = 1
return(word_dict)
try initializing the dictionary outside of the function and then using global inside the function. Is that one item in the dictionary the last iteration?
Fix your indenting in your iterating over the wordlist. Should read:
for item in wordlist:
if item in word_dict.keys():
word_dict[item] += 1
else:
word_dict[item] = 1
this seems to be an indentation and whitespace issue. Make sure the if and else statements near the end of your function are at the same level.
Below is code I got working with the indentation at the correct level. In addition comments to explain the thought process
def createDict():
wordlist = []
with open('superman.txt','r', encoding="utf8") as superman:
for line in superman:
for word in line.split():
wordlist.append(word)
#print(word)
table = str.maketrans("!#$%&()*+, ./:;<=>?#[\]^_`{|}~0123456789'“”-''—", 47*' ' )
lenght = len(wordlist)
i = 0
while i < lenght:
wordlist[i] = wordlist[i].translate(table)
wordlist[i] = wordlist[i].lower()
wordlist[i] = wordlist[i].strip()
i += 1
wordlist = list(filter(str.strip, wordlist))
# print(len(wordlist)) # check to see if wordlist is fine. Indeed it is
word_dict = {}
for item in wordlist:
# for dictionaries don't worry about using dict.keys()
# method. You can use a shorter if [value] in [dict] conditional
# The issue in your code was the whitespace and indentation
# of the else statement.
# Please make sure that if and else are at the same indentation levels
# Python reads by indentation and whitespace because it
# doeesn't use curly brackets like other languages like javascript
if item in word_dict:
word_dict[item] += 1
else:
word_dict[item] = 1
return word_dict # print here too
Please let me know if you have any questions. Cheers!

Python v3 Find The Longest Word (Error Message)

I'm using Python 3.4 and am getting an error message " 'wordlist is not defined' " in my program. What am I doing wrong? Please respond with code.
The program is to find the longest word:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
def main():
wordlist = input("Enter a list of words seperated by spaces ".split()
word, length = find_longestest_word(wordlist)
print (word, "is",length,"characters long.")
main()
Apart from the problems with your code indentation, your find_longest_word() function doesn't really have any logic in it to find the longest word. Also, you pass it a parameter named a, but you never use a in the function, instead you use wordlist...
The code below does what you want. The len() function in Python is very efficient because all Python container objects store their current length, so it's rarely worth bothering to store length in a separate variable. So my find_longest_word() simply stores the longest word it's encountered so far.
def find_longest_word(wordlist):
longest = ''
for word in wordlist:
if len(word) > len(longest):
longest = word
return longest
def main():
wordlist = input("Enter a list of words separated by spaces: ").split()
word = find_longest_word(wordlist)
print(word, "is" ,len(word), "characters long.")
if __name__ == '__main__':
main()
The line "return word, length" is outside any function. The closest function is "find_longest_word(a)", so if you want it to be a part of that function, you need to indent lines 4-7.
Indentation matters in Python. As the error says, you have the return outside the function. Try:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
def main():
wordlist = input("Enter a list of words seperated by spaces ".split()
word, length = find_longestest_word(wordlist)
print (word, "is",length,"characters long.")
main()
In python the indentation is very important. It should be:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
word = (i)
length = len(i)
return word, length
But because of the function name, I think the implementation is wrong.

Categories