Python While Loop: Else tripped despite valid input - python

Doing the CS101 course for the github OSS and I've got a bug with one of the projects where generally it runs fine but with a specific use case(input: o, m, n, ., n) that last 'n' triggers the Else block (even though it prints out 'n' for the variable gameDecision. I've tried everything I can think of but am coming up short. Since the course is closed, any advice would be greatly appreciated. Thanks!
Link to problem: https://courses.edx.org/courses/course-v1:MITx+6.00.1x_8+1T2016/courseware/Week_4/Problem_Set_4/
Code:
# 6.00x Problem Set 4A Template
#
# The 6.00 Word Game
# Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens>
# Modified by: Sarina Canelake <sarina>
#
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# wordList: list of strings
wordList = []
for line in inFile:
wordList.append(line.strip().lower())
print " ", len(wordList), "words loaded."
return wordList
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
#
# Problem #1: Scoring a word
#
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
word: string (lowercase letters)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: int >= 0
"""
# TO DO ... <-- Remove this comment when you code this function
count = 0
for i in word:
count += SCRABBLE_LETTER_VALUES[i]
count *= len(word)
if len(word) == n:
count += 50
return count
#
# Problem #2: Make sure you understand how this function works and what it does!
#
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print letter, # print all on the same line
print # print an empty line
#
# Problem #2: Make sure you understand how this function works and what it does!
#
def dealHand(n):
"""
Returns a random hand containing n lowercase letters.
At least n/3 the letters in the hand should be VOWELS.
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int >= 0
returns: dictionary (string -> int)
"""
hand={}
numVowels = n / 3
for i in range(numVowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(numVowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
#
# Problem #2: Update a hand by removing letters
#
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
# TO DO ... <-- Remove this comment when you code this function
chand = hand.copy()
for i in word:
if chand.get(i,0) == 0:
return False
break
else:
chand[i] -= 1
return chand
#
# Problem #3: Test word validity
#
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
# TO DO ... <-- Remove this comment when you code this function
chand = hand.copy()
if word in wordList and updateHand(chand, word) != False:
return True
else:
return False
#
# Problem #4: Playing a hand
#
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
# TO DO... <-- Remove this comment when you code this function
length = 0
for i in hand:
length += hand.get(i, 0)
return length
def playHand(hand, wordList, n):
"""
Allows the user to play the given hand, as follows:
* The hand is displayed.
* The user may input a word or a single period (the string ".")
to indicate they're done playing
* Invalid words are rejected, and a message is displayed asking
the user to choose another word until they enter a valid word or "."
* When a valid word is entered, it uses up letters from the hand.
* After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
* The sum of the word scores is displayed when the hand finishes.
* The hand finishes when there are no more unused letters or the user
inputs a "."
hand: dictionary (string -> int)
wordList: list of lowercase strings
n: integer (HAND_SIZE; i.e., hand size required for additional points)
"""
score = 0
while calculateHandlen(hand) > 0:
displayHand(hand)
word = raw_input("Please provide a word: ")
if word == ".":
break
else:
if isValidWord(word, hand, wordList) != True:
print "Please enter a valid word"
else:
print "Points scored: " + str(getWordScore(word, n))
score += getWordScore(word, n)
hand = updateHand(hand,word)
print "Game over! Total score: " + str(score)
#
# Problem #5: Playing a game
#
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', let the user play a new (random) hand.
* If the user inputs 'r', let the user play the last hand again.
* If the user inputs 'e', exit the game.
* If the user inputs anything else, tell them their input was invalid.
2) When done playing the hand, repeat from step 1
"""
n = random.randint(3,9)
hand = dealHand(n)
gameDecision = raw_input("Input 'n' or 'r' or 'e': ")
quitting = False
while quitting == False:
if gameDecision == "n":
n = random.randint(3,9)
hand = dealHand(n)
playHand(hand, wordList, n)
gameDecision = raw_input("Input 'n' or 'r' or 'e': ")
if gameDecision == "r":
playHand(hand, wordList, n)
gameDecision = raw_input("Input 'n' or 'r' or 'e': ")
if gameDecision == "e":
quitting = True
else:
print "Input is invalid"
gameDecision = raw_input("Input 'n' or 'r' or 'e': ")
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
wordList = loadWords()
playGame(wordList)

Because of the way you formed this block:
if gameDecision == "n":
n = random.randint(3,9)
hand = dealHand(n)
playHand(hand, wordList, n)
gameDecision = raw_input("Input 'n' or 'r' or 'e': ")
if gameDecision == "r":
playHand(hand, wordList, n)
gameDecision = raw_input("Input 'n' or 'r' or 'e': ")
if gameDecision == "e":
quitting = True
else:
print "Input is invalid"
gameDecision = raw_input("Input 'n' or 'r' or 'e': ")
The else case is tied to the if case for the "e" character. You should be using "elif" statements for the "r" and "e" case.

Related

How can i print number of times each alphabet occurs in the string?

Well i was trying to write an code for isogram in python as my assignment so i got stuck here
I considered following things
1.All the words entered are in small
2. It only contains alphabets and no special characters or numbers
word =input("enter the word ")
list_of_alphabets = list(word)
no_of_alphabets = len(list_of_alphabets)
for i in range(no_of_alphabets):
number = list_of_alphabets.count()
print (number)
I got stuck here now i want the for loop to check whether each alphabet occurs once or not and print number of times each alphabet occurs. If not then it should print not an isogram , and print an isogram if it is. Also if there is some other way to this code i would also like that
PS. Please don't suggest me the code from geeksforgeek as i have already seen it
Just use collections.Counter:
>>> c = Counter('gallahad')
>>> c
Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
If you need to check how many specific symbols are in your string, use count method:
>>> 'gallahad'.count("a")
3
Corrections to your posted code.
Changes to your code
word = input("enter the word ")
#list_of_alphabets = list(word) -- not needed
#no_of_alphabets = len(list_of_alphabets) -- not needed
#for i in range(no_of_alphabets): -- change to following
for letter in word: # loop through each letter in word
number = word.count(letter)
if number > 1:
print("Not a isogram")
break
else:
# Will enter here only if did not encounter break in above for loop
print("Is a isogram")
After cleaning up the above we have
word = input("enter the word ")
for letter in word:
number = word.count(letter)
if number > 1:
print("Not a isogram")
break
else:
print("Is a isogram")
Alternative Suggested by Daniel Hao
Using Python sets
word = input("enter the word ")
if len(word) == len(set(word)):
print("Is a isogram")
else:
print("Not a isogram")
as per#dukkee opinion. You can also try this
value ="gallahad"
print({i:value.count(i) for i in value})

How do I choose 2 or more letters in a word?

Basically my plan was to return text with random-sized letters in words i.e. "upper" or "lower". The script is working, though it seems raw (I am a Beginner and I'd appreciate some corrections from You).
The problem is:
It is not consistent. With that said, it can print word 'about' even if it should be 'About' or something similar.
I want to be sure that the maximum of UPPER or lower letters in a row do not exceed 3 letters. and I don't know how to do it.
Thank you in advance.
#!/usr/bin/env python3
import random
message = input()
stop = ''
def mocking(message):
result = ''
for word in message:
for letter in word:
word = random.choice(random.choice(letter.upper()) + random.choice(letter.lower()))
result += word
return result
while stop != 'n':
print(mocking(message))
stop = input("Wanna more? y/n ").lower()
if stop == 'n':
break
else:
message = input()
You need to split the input into words, decide how many positions inside the word you want to change (minimum 3 or less if the word is shorter).
Then generate 3 unique positions inside the word (via random.sample) to change, check if upper then make lower else make upper. Add to resultlist and join words back together.
import random
message = "Some text to randomize"
def mocking(message):
result = []
for word in message.split():
len_word = len(word)
# get max 3 random positions
p = random.sample(range(len_word),k = min(len_word,3))
for position in p:
l = word[position]
if l.isupper():
word = word[:position] + l.lower() + word[position+1:]
else:
word = word[:position] + l.upper() + word[position+1:]
result.append(word)
return ' '.join(result)
while True:
print(mocking(message))
stop = input("Wanna more? y/n ").lower()
if stop == 'n':
break
else:
message = input()
See Understanding slice notation for slicing
At most 3 modifications? I would go with something like this.
def mocking(message):
result = ''
randomCount = 0
for word in message:
for letter in word:
newLetter = random.choice( letter.upper() + letter.lower() )
if randomCount < 3 and newLetter != letter:
randomCount += 1
result += newLetter
else:
result += letter
randomCount = 0
return result
If the random choice has modified the letter then count it.

How do I put all the items in a list through a looping function?

This program inputs all of the items into the letter[] list and is supposed to loop them them in to go through the getLetter function but it isn't working. The program below only outputs the last item of the list through the getLetter function.
import time, sys
def getLetter(letter):
while True:
if letter =='A'or letter=='a':
print(' * ')
return
break
if letter =='B'or letter=='b':
print(' ** ')
return
break
print('Enter each character individually')
letterInput=[]
while True:
print('Enter letter number ' + str(len(letterInput)+1),end='')
print('. Enter nothing to stop.')
time.sleep(0.5)
letter = input()
if letter == '':
break
letterInput=letterInput+[letter]
print('These are the letters you have inputted:')
for letter in letterInput:
print(' '+letter)
while True:
for i in range(len(letter)):
output=getLetter(letter[i])
to append an item to a list you should use:
letterInput.append(letter)
You code has more problems:
I tried to fix it but I not really know what the script should do.
See:
import time, sys
def getLetter(letter):
if letter == 'A' or letter == 'a':
return ' * '
if letter == 'B' or letter == 'b':
return ' ** '
return ''
print('Enter each character individually')
letterInput = []
while True:
print('Enter letter number ' + str(len(letterInput) + 1), end='')
print('. Enter nothing to stop.')
time.sleep(0.5)
letter = input()
if letter == '':
break
letterInput.append(letter)
print('These are the letters you have inputted:')
for letter in letterInput:
print(' ' + letter)
for letter_value in letterInput:
output = getLetter(letter_value)
print(output)
Like #Samwise in comments said, you could use this:
def getLetter(letter):
# letter is 'a' or 'A'
if letter.lower() == 'a':
return ' * '
# letter is 'b' or 'B'
if letter.lower() == 'b':
return ' ** '
# letter is NOT 'a', 'A', 'b' or 'B'
return ''
Admittedly, I'm presuming upon some gaps left in the description about how you want the output to work, so this is just an example of some major simplifications which can be applied.
Here are some more Pythonic methods which can be used in place of your JavaScript-like syntax:
def getLetter(letters):
for i in letters:
if i.lower() =='a':
print(' * ')
elif i.lower() == 'b':
print(' ** ')
letters = input('Enter a string of letters: ')
print('These are the letters you have inputted: ', letters)
getLetter(letters)
Input:
abcdef
Output:
These are the letters you have inputted: abcdef
*
**
Here's my attempt at cleaning up this script to make it work better and hopefully to make it easier for you to add on to it. Some specific notes:
Don't put everything in while True loops for no reason. It makes sense in the context of your input loop; in the other places it seems like you're doing it for no particular reason, and it's very likely to make your program hang since you don't have a way to ensure that the loop is broken in each case.
The standard convention in Python is to name things like get_letter instead of getLetter. This is a good habit to establish early!
I implemented your get_letter function in such a way as to reduce code duplication and to have it raise an exception if it gets unexpected input, rather than hanging forever.
Use for letter in letters rather than for i in range(len(letters))!
Use letters.append(letter) rather than letters = letters + [letter].
Get familiar with f"strings" and str.join(); these are really useful ways to format strings easily.
import time
def get_letter(letter: str) -> str:
letter_symbols = {
'a': '*',
'b': '**',
}
return f' {letter_symbols[letter.lower()]} '
print('Enter each character individually')
letters = []
while True:
print(
f"Enter letter number {(len(letters)+1)}. "
"Enter nothing to stop."
)
time.sleep(0.5)
letter = input()
if not letter:
break
letters.append(letter)
print('These are the letters you have inputted:')
print(' '.join(letters))
for letter in letters:
print(get_letter(letter))

Python String Help Hawaiian Word Pronunciation

I am having trouble figuring out why my code is not printing out anything after I input a value for word. I can input a word, but it does not output anything after evaluating through the while loop. What are your thoughts?
ai = "eye-"
ae = "eye-"
ao = "ow-"
au = "ow-"
ei = "ay-"
eu = "eh-oo-"
iu = "ew-"
oi = "oy-"
ou = "ow-"
ui = "ooey-"
a = "ah-"
e = "eh-"
i = "ee-"
o = "oh-"
u = "oo-"
p = "p"
k = "k"
h = "h"
l = "l"
m = "m"
n = "n"
word = input("Please enter a Hawaiian word you want pronounced")
character_count1 = int(0)
character_count2 = int(1)
pronunciation = ""
while character_count1 < len(word):
if word[character_count1:character_count2] == ai or word[character_count1:character_count2] == "ae"or word[character_count1:character_count2] == "ao"or word[character_count1:character_count2] == "ei"or word[character_count1:character_count2] == "eu"or word[character_count1:character_count2] == "iu"or word[character_count1:character_count2] == "oi"or word[character_count1:character_count2] == "ou":
print("your word",pronunciation + word[character_count1:character_count2])
character_count1 + 2 and character_count2 + 2
elif word[character_count1:character_count1] == a or word[character_count1:character_count1] == e or word[character_count1:character_count1] == i or word[character_count1:character_count1] == o or word[character_count1:character_count1] == p or word[character_count1:character_count1] == k or word[character_count1:character_count1] == h or word[character_count1:character_count1] == l or word[character_count1:character_count1] == m or word[character_count1:character_count1] == n:
print("your word",pronunciation + word[character_count1:character_count1] )
character_count1 + 1 and character_count2 + 1
What are you trying to achieve is pretty easy, if you use a data structure called dictionary, a very basic data structure in python. Change the data structure like that:
dic={"ai" :"eye-","ae" :"eye-","ao": "ow-","au" :"ow-"......}
Now you can access the values (Pronunciation) with the keys (words).
like this,
dic["ai"]
You will get:
eye-
So, now let's try to get the solution:
Define a dictionary.
dic={"ai" :"eye-","ae" :"eye-","ao": "ow-","au" :"ow-"......}
Take the input, better use raw_input if you are not using python3
word = raw_input("Please enter a Hawaiian word you want pronounced")
Split the input by white spaces and form a list.
lst=word.split()
Use the elements of lst as dictionary key to find the value. Iterate through the list and check if the input matches to any key of dic
for i in lst:
print dic.get(i)
None will be printed if the key doesn't exist.
As, your requirement isn't quite clear to me, i have included all the things needed to solve the problem.
So, use them where needed and solve the problem.
Happy coding.
The folks in the answers and comments who have said "use a dictionary" are right, but you can't just loop through the input a character at a time because you have overlapping matches. Without looking at the next character, you can't tell if "a" is part of "ai" or "an", and those cases are handled differently. Here is a complete solution with annotation that handles the subtlety and provides an informative error message when you encounter an illegal string.
hawaiian_pronunciation = {
"ai": "eye-",
"ae": "eye-",
"ao": "ow-",
"au": "ow-",
"ei": "ay-",
"iu": "ew-",
"oi": "oy-",
"ui": "ooey-",
"a": "ah-",
"e": "eh-",
"i": "ee-",
"o": "oh-",
"u": "oo-",
"p": "p",
"k": "k",
"h": "h",
"l": "l",
"m": "m",
"n": "n"
}
def segment(word, start):
# we have to consider the longest possible segment first
# so that hai gets tokenized h-ai instead of h-a-i
for length in (2,1):
# check if the length of the segment puts us past the end of the word
# the upper bound can be equal to the length of the word since the
# string[upper_bound] is not actually included in the range
if start+length > len(word):
continue
# the input segment we are considering
input = word[start:start+length]
# is it in our dictionary?
if input in hawaiian_pronunciation:
# if it is get the corresponding pronunciation
output = hawaiian_pronunciation[input]
# return the output and length for a successful match
return output, length
# if no candidate matches, raise an exception describing where you were
# when you failed to find a match
raise Exception("cannot match word {} at position {}, bad segment {}",
word, start, word[start:])
def pronounce(word):
"generate pronunciation from word"
# build a list of strings
out = []
# we have to use a while loop and an explicit index
# because we can jump by one or two spaces depending on the length of the match
start = 0
while start < len(word):
# when we get a match, append the new sound and
# advance the appropriate number of spaces
new_sound, length = segment(word, start)
out.append(new_sound)
start += length
return "".join(out)
def main():
print pronounce("hai")
main()

Python boggle game

I'm trying to finish this boggle game Python challenge for school, and I've created a draw board function that creates a board with 16 random letters. How do I use a def function to ask the user to input a word and then score it, depending on how long the word is? Once that is completed, the game should work properly. Any help will be greatly appreciated :)
import random
def loadwords ():
print "Loading word list from file.. "
wordList = []
inFile = open ('words.txt','r')
for line in inFile:
wordList.append(line.strip().lower())
#inFile : locates file in the folder, opens it
#wordlist: list of the words (strings)
print " " , len(wordList), "words loaded"
inFile.close()
return wordList
def spellCheck (word, wordList):
if (word in wordList) == True:
return True
else:
return False
def drawBoard (randomLetters):
'''Takes a randomList of 16 characters
Prints out a 4 x 4 grid'''
print " %s %s %s %s " %(randomLetters [0], randomLetters [1], randomLetters [2], randomLetters [3])
print " %s %s %s %s " %(randomLetters [4], randomLetters [5], randomLetters [6], randomLetters [7])
print " %s %s %s %s " %(randomLetters [8], randomLetters [9], randomLetters [10], randomLetters [11])
print " %s %s %s %s " %(randomLetters [12], randomLetters [13], randomLetters [14], randomLetters [15])
def wordinput ():
#asks user to input the longest word they can from grid
wordinput = raw_input ("Enter a word made up of the letters in the 4x4 table")
for letters in wordinput:
letters == randomLetters
def randomLetters ():
letters = []
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','v','w','x','y','z']
for i in range (0,16,1):
letters.append(random.choice(alphabet))
return letters
dictionary = loadwords()
letterList = randomLetters()
drawBoard(letterList)
wordinput(randomLetters)
raw_input (in Python 2) or input (in Python 3) allows to read a string.
Then you need to check if all the letters are contained in the alphabet...
def wordInLetter(word, letters):
for i in range(word):
if word[i] not in letters:
return False
return True
Or shorter:
def wordInLetter(word, letters):
return all(letter in letters for letter in word)
But wait, you don't want to make it possible to use one letter several times!
Let's use the Counter to track how many times every letter is in the letter bag and work from that:
from collections import Counter
def wordInLetter(word, letters):
available = Counter(letters)
for letter in word:
if available[letter] == 0:
return False
available[letter] -= 1
return True
This seems to work nicely. I hope this is what you need.
In [3]: wordInLetter('kos','akos')
Out[3]: True
In [4]: wordInLetter('kos','ako')
Out[4]: False
In [5]: wordInLetter('koss','akos')
Out[5]: False
EDIT
So we're not only interested about whether word can be combined in letters, but we also want to know if it can be done by matching adjacent letters. So another try:
import math
def wordInLetterSearch(word, letters, startX, startY):
# Assume: letters is a list of X letters, where X is a k*k square
k = int(len(letters) ** 0.5)
if len(word) == 0:
return True
def letter(x, y):
return letters[x + y*k]
def adjacent(x, y):
if x > 0:
yield x-1, y
if x < k-1:
yield x+1, y
if y > 0:
yield x, y-1
if y < k-1:
yield x, y+1
# try to move in all 4 directions
return any(letter(x2, y2) == word[0] and wordInLetterSearch(word[1:], letters, x2, y2)
for x2, y2 in adjacent(startX, startY))
def wordInLetter(word, letters):
k = int(len(letters) ** 0.5)
def coords(i):
return i%k, i/k
# look for a starting point
return any(letter == word[0]
and wordInLetterSearch(word[1:], letters,
coords(i)[0], coords(i)[1])
for i, letter in enumerate(letters)) coords(i)[1])
for i, letter in enumerate(letters))
This is a bit complicated. Basically it's a 2-step search: First we look for a starting point (a position inside letters where the letter matches the first character of the word), then we move snake-like to adjacent fields where possible, recursively.
Little modification is required to match Boggle rules exactly:
modify adjacent to allow diagonals too (easy),
prevent visiting the same spot twice (medium; hint: add a parameter to wordInLetterSearch, use a set).
I'll leave these as an exercise.
Here is another variant. It should be easier to read but the idea is the same: simple backtracking. Sometimes, it is easier to abort the iteration on the caller-side (no not execute the next step), sometimes on the calle-side (on every iteration, check precondition and abort if invalid).
def wordInBoardIter(letters, word, x, y):
n = int(len(letters)**0.5)
if word == "": return True # empty - all letters are found
if x<0 or y<0 or x>=n or y>= n: return False #outside of board
if letters[x+y*n] != word[0]: return False # we are looking at the wrong position
# one step further:
return any(wordInBoardIter(letters, word[1:], x+dx,y+dy) for dx,dy in [(1,0), (0,1), (-1,0), (0,-1)])
def wordInBoard(letters, word):
n = int(len(letters)**0.5)
return any(any(wordInBoardIter(letters, word, x,y) for x in range(n)) for y in range(n))
if __name__ == '__main__':
letters = ['a', 'h', 'e', 'l',
'x', 'd', 'l', 'l',
'y', 'v', 'r', 'o',
'z', 'w', 'o', 'w']
print "hello : %s" % ("found" if wordInBoard(letters, "hello") else "not found")
print "helloworld: %s" % ("found" if wordInBoard(letters, "helloworld") else "not found")
print "foobar : %s" % ("found" if wordInBoard(letters, "foobar") else "not found")
There are the same exercises in this version (diagonal tiles and disallowing the reuse the same letters twice).
I haven't played boggle much myslef, but a solution you could use to do this would be to take the word the user inputted and use the len() command to return the length of the word. Then take that length and score it. Here's a basic example (modify it to fit the rules of the game):
def wordinput ():
#asks user to input the longest word they can from grid
wordinput = raw_input ("Enter a word made up of the letters in the 4x4 table")
for letters in wordinput:
letters == randomLetters
scoreWord(wordInput)
def scoreWord(word)
#finds the amount of characters in the word
wordLength = len(word)
#multiplies the maunt of letters in the word by two to get the score
#(not sure how boggle scoring works)
score = wordLength * 2

Categories

Resources