My except won't print when len(line.strip()) == d gets None.
def isPalindrome(word):
if len(word) < 1:
return True
else:
if word[0] == word[-1]:
return isPalindrome(word[1:-1])
else:
return False
def fileInput(filename):
palindromes = False
fh = open(filename, "r")
length = input("Enter length of palindromes:")
d = int(length)
try:
for line in fh:
for s in str(len(line)):
if isPalindrome(line.strip()):
palindromes = True
if (len(line.strip()) == d):
print(line.strip())
except:
print("No palindromes found for length entered.")
finally:
fh.close()
Your code is failing because your exception is not the only place where non-existence of d-length palindromes in your input file takes you.
You need to check for the value of palindromes as well.
So, at the end of your try-block, add a line that prints "no palindromes found", like so:
def fileInput(filename):
palindromes = False
# more code
try:
# more code
if not palindromes:
print("No palindromes found for length entered.")
except:
print("No palindromes found for length entered.")
finally:
# more code
By the way, I would clean up your function as follows:
def isPalindrome(word):
if not len(word): # is the same as len(word) == 0
return True
elif word[0] == word[-1]: # no need for overly nested if-else-blocks
return isPalindrome(word[1:-1])
else:
return False
def fileInput(filename):
palindromes = False
d = int(input("Enter length of palindromes:"))
with open(filename) as fh: # defaults to "r" mode. Also, takes care of closing the file for you
for line in fh:
word = line.strip()
if isPalindrome(word) and len(word) == d: # note that you didn't have the len(word)==d check before. Without that, you don't check for the length of the palindrome
palindromes = True
print(word)
if not palindromes:
print("No palindromes found for length entered.")
Related
I need to write a code that prints out valid or invalid for an input of letters and numbers for a license plate. The conditions are: first two characters must be letters, characters have to be between 2 and 6, and if numbers are used, 0 should not be the first, nor should a number appear before a letter.
I put the code below on Thonny and cannot understand why len(l) == 4 part of the conditional statement for def valid_order() returns None and does not execute the next line of the code whereas others work fine. My code should return "Valid" for CSAA50, but it returns invalid. Why?
Also, is there an elegant way to write def valid_order()?
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s[0:2].isalpha() and 6 >= len(s) >= 2 and s.isalnum() and valid_order(s):
return True
else:
return False
def valid_order(c):
n = []
l = list(c[2:len(c)])
for i in c:
if i.isdigit():
n += i
if n and n[0] == "0":
return False
if len(l) == 2:
if l[0].isdigit() and l[1].isalpha():
return False
if len(l) == 3:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha():
return False
else:
if l[1].isdigit() and l[2].isalpha():
return False
if len(l) == 4:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha() or l[3].isalpha():
return False
else:
if l[1].isdigit():
if l[2].isalpha() or l[3].isalpha():
return False
else:
if l[2].isdigit() and l[3].isalpha():
return False
else:
return True
main()
I know there are already countless clones of Wordle. Nevertheless I try to program my own version.
In the function is_real_word it should be checked whether the entered word of the user occurs in the word list. If so, the variable check = True.
However, the FOR loop is always exited when the counter is at 1.
The file "5_letter_words.txt" contains 3 entries: wetter, wolle, watte
And last but not least also the return value for eingabewort is sometimes NONE. And I don't know why?
import random
def word_list():
wordle = []
with open("5_letter_words.txt", "r") as file:
for line in file:
myTuple = line.strip()
wordle.append(myTuple)
return wordle
def random_word(wordlist):
return random.choice(wordlist)
def is_real_word(guess, wordlist):
for word in wordlist:
if guess == word:
return True
return False
def check_guess(guess, randomword):
randomword_tuple = []
guess_tuple = []
length = len(randomword)
output = ["-"] * length
for index in range(length):
if guess[index] == randomword[index]:
output[index] = "X"
randomword = randomword.replace(guess[index], "-", 1)
for index in range(length):
if guess[index] in randomword and output[index] == "-":
output[index] = "O"
randomword = randomword.replace(guess[index], "-", 1)
return ''.join(output)
def next_guess(wordlist):
guess = input('Please enter a guess: ')
guess = guess.lower()
valid = is_real_word(guess, wordlist)
if valid == False:
print('Thats not a real word!')
next_guess(wordlist)
else:
return guess
def play():
target = []
target = word_list()
zufallswort = str()
zufallswort = random_word(target)
eingabewort = next_guess(target)
print('Eingabewort: ', eingabewort)
print('Zielwort: ', zufallswort)
play()
Could you check if your function word_list returns the list?
You dont give a clear path, only the file name.
If it works, try:
def is_real_word(guess, wordlist):
for word in wordlist:
if guess == word:
check = 1
break
return check
I have this linear search where there is a list of words and a single word. the search checks whether the word is in the list or not. I keep on trying to pass my parameters to test the function but when i run the program nothing comes up. it would be great if you could look at this code and tell me where im going wrong.
def isin(alist, word):
found = False
length = len(alist)
pos = 0
while found == False and pos < length:
if alist[pos] == word:
found == True
else:
pos = pos + 1
return found
words = ["child","adult","cat","dog","whale"]
if isin(words, "dog"):
print("yes")
else:
print("no")
You are doing a lot extra works. Do it like this:
def isin(alist, word):
if word in alist:
return True
else:
return False
words = ["child","adult","cat","dog","whale"]
if isin(words, "dog"):
print("yes")
else:
print("no")
You have a problem with line found == True. It should be found = True.
def isin(alist, word):
found = False
length = len(alist)
pos = 0
while found == False and pos < length:
if alist[pos] == word:
found = True
else:
pos = pos + 1
return found
You could simplify the method to do the same task in one line as:
def isin(alist, word):
return True if word in alist else False
I have a code that seems to have a slight issue it reads the file... But the issue is it can not identify the words/letters this is what i mean extract('test.txt',('A','E','I','O','U')) the test.txt is a txt file and the ('A','E','I','O','U') is the words i want to find.
my code:
def extract(file,find=()):
with open(str(file),'r') as file:
find = list(find)
read_file = file.readlines()
num1 = 0
num = num1-1
for vals in find:
num1 += 1
pass
for finds in read_file:
linef = str(finds)
main_obj = find[num]
if main_obj in linef:
print("Yay")
elif linef != main_obj:
print("NO")
else:
print("???")
pass
extract('test.txt',('A','E','I','O','U'))
What my output is:
NO
NO
NO
NO
Yay
This is the expected output:
Yay
Yay
Yay
Yay
Yay
inside test.txt:
A
E
I
O
U
I'll just leave this here. If the end result is to compare each variable inside of find to each line in file then this should do the job:
def extract(file, find=()):
with open(file) as F:
contents = F.readlines()
for line in contents:
if any([i in line for i in find]):
print("Yay")
else:
print("NO")
extract("test.txt", ('A','E','I','O','U'))
You just need to update your logic and remove this code. because it will always return -1 index on every increment.
num1 = 0
num = num1-1
for vals in find:
num1 += 1
pass
Just use one variable and increment it accordingly.
def extract(file, find=()):
num = 0
with open(str(file), 'r') as file:
find = list(find)
print(find)
read_file = file.read().splitlines()
print(read_file)
for finds in read_file:
linef = str(finds)
main_obj = find[num]
num += 1
if main_obj in linef:
print("Yay")
elif linef != main_obj:
print("NO")
else:
print("???")
pass
In the code:
for finds in read_file:
linef = str(finds)
main_obj = find[num]
if main_obj in linef:
print("Yay")
elif linef != main_obj:
print("NO")
you never increment num and hence are essentially always comparing find[-1] with main_obj. I guess you have to increment num if there is a match or whatever your requirement is.
if main_obj in linef:
num += 1
print("Yay")
Either way, this would be the most down-to-earth correct way to do what you are required to:
for temp in find:
not_found = True
for finds in read_files:
if temp in finds:
not_found = False
print("Yay")
break
elif temp != finds:
not_found = True # elif is not needed TBH but just adding for clarity
if not_found:
print("NO")
I am trying to append the incorrect words to a list, however when I print the list outside of the function it is empty and when I print it inside the function it prints a list for each word. How do I get the list to print just one time with the incorrect words in it at the end of the program?
File 1:
this is my spell checker program
File 2: dis is my spll cheker program
So there are 3 incorrect words that should be added to the list
word_list = []
if cmdlength != 2:
print ("Usage error, expected 2 args got " + str(cmdlength))
exit()
else:
try:
f = open(sys.argv[1])
f.close()
except FileNotFoundError:
print("File does not exist")
exit()
try:
ff = open(sys.argv[2])
ff.close()
except FileNotFoundError:
print("File does not exist")
exit()
word = ""
with open(sys.argv[1],"r") as fh:
while True:
ch=fh.read(1)
if ch == " " or ch == "\n" or ch == ":" or ch == ".":
with open(sys.argv[2],"r") as fh2:
def check_word(word,fh2,word_list):
lines = fh2.readlines()
for line in lines:
x= re.search(word,line)
if x:
#correctwords
print(word + ": " + "0")
#count += 1
else:
#incorrect words
print(word, ": " , "1")
word_list.append(word)
#count2 += 1
check_word(word,fh2,word_list)
word = ''
else:
word += ch
if not ch:
print(word)
print("End of file")
print(word_list)
break
The function is missing a return statement to return word_list.
This should work
...
def check_word(word,fh2,word_list):
lines = fh2.readlines()
for line in lines:
...
word_list.append(word)
#count2 += 1
return word_list
word_list = check_word(word,fh2,word_list)