Overview :
Problem tutorial: HackerRank minion game practice tutorial
Input: BAANANAS
Expected output: Kevin 19
My output: Kevin 18
As you can see, I'm off-by-one, but I really can't figure out exactly where the error would be.
Here's the code :
def minion_game(string):
# your code goes here
vowels = ('A', 'E', 'I', 'O', 'U')
def kevin(string):
kevin_list = []
for i in range(len(string)):
if string[i] in vowels:
return len(string) - i
#Find every possible combination beginning with that letter
for j in range(len(string)):
#Gets rid of white-space characters...for some reason....
if j >= i and string[i:j+1] not in kevin_list:
kevin_list.append(string[i:j+1])
return kevin_list
def stuart(string):
stuart_list = []
for i in range(len(string)):
if string[i] not in vowels:
#Find every possible combination beginning with that letter
for j in range(len(string)):
#Gets rid of white-space characters...for some reason....
if j >= i and string[i:j+1] not in stuart_list:
stuart_list.append(string[i:j+1])
return stuart_list
def points(words):
points_list = []
for substring in words:
points_list.append(string.count(substring))
return sum(points_list)
def calculateWinner(player1, score1, player2, score2):
if score1 > score2:
return '%s %d' %(player1, score1)
elif score2 > score1:
return '%s %d' %(player2, score2)
else:
return 'Draw'
#print(kevin(string))
#print("points:", points(kevin(string)))
print(calculateWinner("Stuart", points(stuart(string)), "Kevin", points(kevin(string))))
Anything commented out was probably used for debugging (except for the comments themselves)
(Note: the function is called inside main(), so it's being called, don't worry. This is just the definition of it)
Try this code. It is much simpler and more efficient.
def minion_game(string):
stuCount=kevCount=0
N=len(string)
for i in range(N):
if string[i] in "AEIOU": # A vowel letter
kevCount+=N-i
else:
stuCount+=N-i # A consonant letter
if stuCount > kevCount:
print("Stuart"+" "+str(stuCount))
elif kevCount > stuCount:
print("Kevin"+" "+str(kevCount))
else:
print("Draw")
Nevermind.
The .count() method in BAANANAS does not count the substring "ANA" twice if it overlaps.
As in the following:
BA[ANA]NAS vs. BAAN[ANA]S
It only counts one of these, not both.
Related
does anyone know how to translate robber's languge to English in python?
like this one but in reverse?
def translate(s):
consonants = 'bcdfghjklmnpqrstvwxz'
return ''.join(a + 'o' + a if a in consonants else a for a in s)
print(translate("hej"))
Maybe something like:
def translate(s):
consonants = 'bcdfghjklmnpqrstvwxz'
counter = 0
outputcounter = 0
output = s
while counter < len(s):
char = s[counter]
if char in consonants:
output = output[:outputcounter] + char + output[outputcounter + 3:]
counter += 3
outputcounter += 1
else:
counter += 1
outputcounter += 1
return output
Try it out! (I don't know if that's nice code style, but however)
Here is an alternative approach
Since this is an interesting problem, I decided to have a go myself. Here is an efficient way of writing your first function with O(1) set lookup:
def translate_english_robber(s):
consonants = 'bcdfghjklmnpqrstvwxz'
# using a set instead is more efficient
lookup = set(consonants + consonants.upper())
result = ""
for char in s:
if char in lookup:
# anonymous function for converting the case of the letter "o"
convert_case = lambda x: "o" if x.islower() else "O"
# add it to the result
result += char + convert_case(char) + char
else:
result += char
return result
Then for the reverse translation, all you need to do is find a consonant, and append it to the list, then somehow remove the next 2 characters, and continue the next iteration after the last removed character. Otherwise, if the current character is not a constant, add it normally.
For example, If my Robbers language was "hohey", I would first find "h", add it, and remove "o" and "h" after that, then start iterating from "e". In the end, we would have "hey" as the English translation.
Using an iterator would be useful here. You can also read up on iterators here, they are quite useful for problems like this.
Here is my attempt:
def translate_robber_english(s):
consonants = 'bcdfghjklmnpqrstvwxz'
lookup = set(consonants + consonants.upper())
# create the iterator
it = iter(list(s))
result = ""
# loop till we reach the end
while True:
try:
# get the current letter
current = next(it)
# add it regardless
result += current
# if consonant, skip the next to letters
if current in lookup:
next(it)
next(it)
# If this exception occurs, break out of the loop
except StopIteration:
break
return result
And now you can get the reverse translations with both the above functions:
>>> robber = translate_english_robber("black")
>>> print(robber)
boblolacockok
>>> english = translate_robber_english(robber)
>>> print(english)
black
You can try something like this:
def reverse_translate(s):
vowel = ['a', 'e', 'i', 'o', 'u']
final = []
for i in range(len(s)):
if s[i] in vowel:
final.append(s[i])
else:
try:
if s[i] == s[i + 2]:
final.append(s[i:i + 3])
except IndexError:
pass
for j, i in enumerate(final):
if i == 'o':
try:
if final[j] == final[j + 1]:
pass
else:
del final[j]
except IndexError:
del final[j]
return "".join(list(map(lambda x: x[0], final)))
Now test_cases:
Normal test_case:
print(reverse_translate('boblolacockok'))
output:
black
But if text also include 'o' as vowel now :
print(reverse_translate('boblolocockok'))
output:
block
vowel = "aeiou"
for i in range(0:len(s)):
if s[i] in vowel == True
count += 1
print("Number of vowels: "+str(count))
The above code doesn't throw any errors in Spyder. I am taking an online course, s is a predefined variable which contains a string. Here I defined s as "big black car"
I have to count the vowels in the string.
When I press enter after typing the code in, I am moved to the next line, nothing happens, I am prompted for more input.
What am I doing wrong?
Working code for you:
s="big black car"
vowel = "aeiou"
count = 0
for i in range(len(s)):
if s[i] in vowel:
count += 1
print("Number of vowels: "+str(count))
Note: First of all, you should use range (len(s)). Second thing is that s[i] in vowel == True will return False. You can easy check it in python console.
>>> 'a' in 'a'
True
>>> 'a' in 'a' == True
False
>>> ('a' in 'a') == True
True
According to my best knowledge Python firstly execute 'a' == True that gives False, then execute 'a' in False. That's why condition is False. Extra parentheses fix that problem.
EDIT: tripleee point that you can use range(len(s)) :).
You need to fix the following:
Get rid of the 0:
Replace the == True with a :
Indent the count += 1 4 spaces to the right
So your code should look as follows:
vowel = "aeiou"
for i in range(len(s)):
if s[i] in vowel:
count += 1
print("Number of vowels: "+str(count))
You can further reduce it to:
vowel = "aeiou"
for i in range(len(s)):
count += s[i] in vowel
print("Number of vowels: "+str(count))
And then further reduce it to:
vowel = "aeiou"
count = sum([s[i] in vowel for i in range(len(s))])
print("Number of vowels: "+str(count))
And then further reduce it to:
vowel = "aeiou"
print("Number of vowels: "+str(sum([s[i] in vowel for i in range(len(s))])))
And then further reduce it to:
vowel = "aeiou"
print("Number of vowels: ", sum([s[i] in vowel for i in range(len(s))]))
And then further reduce it to:
print("Number of vowels: ", sum([s[i] in "aeiou" for i in range(len(s))]))
I'm tutoring a friend in python, not great at it myself. The assignment is to write a script that reverses some made up alien language in which they repeat every vowel-sequence after adding the letter "p". Some examples:
tomato -> topomapatopo groovy->groopoovy and beautiful -> beaupeautipifupul
The goal is to reverse this. From groopoovy -> groovy.
As it is a dutch assignment, there is an exception: "ij" is seen as a vowel. So blijpij -> blij (which complicates things a lot, I find)
My solution seems quite bulky to me and I am interested in a better, more elegant solution. As this is an introduction course to programming, basics are key, unfortunately.
word = input()
vowels = ('a', 'e', 'i', 'o', 'u')
position = 0
solution = ""
while position < len(word):
if word[position] == 'p': # obviously, search for the letter 'p'
add = 1 # keep track of the sub string size
group = ""
while True: # loop to get consecutive vowels
if word[position + add] in vowels:
group += word[position + add]
if word[position + add] == 'i' and word[position + add + 1] == 'j': # recognize the "ij"
group += 'j'
add += 1
add += 1
else:
break
if position+add == len(word): # stay within the bounds of the string
break
add -= 1
if word[position - add:position].lower() == group.lower() and group != "":
position += add
else:
solution += 'p'
else:
solution += word[position]
position += 1
print(solution)
How about this, for an introductory Python class.
There are several example words at the top; just change the comments #.
Instead of checking for "p" on every step, I check for the beginning of a vowel sequence. This sequence will always be terminated by "p". That's the only case where you don't want to append the character to the solution; instead you want to skip to the end of the vowel sequence.
The fact that "ij" is a vowel doesn't create a special case, since "i" begins a vowel sequence.
word = "poopoo-poopoo"
# word = "poopooh"
# word = "hijipijinks"
# word = "apapepe"
# word = "copovfepefepe"
vowels = ('a', 'e', 'i', 'o', 'u')
position = 0
solution = ""
vowel_count = 0 # consecutive vowels
while position < len(word):
c = word[position]
if vowel_count > 0:
if c == 'p':
position += vowel_count + 1
vowel_count = 0
continue
vowel_count += 1
else:
if c in vowels:
vowel_count = 1
solution += c
position += len(c)
print(solution)
import re
input_text = "tomato"
encoded = re.sub('([aeiou]+)','\\1p\\1',input_text)
print(encoded)
decoded = re.sub('([aeiou]+)p\\1','\\1',encoded)
print(decoded)
should do just that
I am completing this HackerRank coding challenge. Essentially, the challenge asks us to find all the substrings of the input string without mixing up the letters. Then, we count the number of substrings that start with a vowel and count the number of substrings that start with a consonant.
The coding challenge is structured as a game where Stuart's score is the number of consonant starting substrings and Kevin's score is the number of vowel starting substrings. The program outputs the winner, i.e. the one with the most substrings.
For example, I created the following code:
def constwordfinder(word):
word = word.lower()
return_lst = []
for indx in range(1,len(word)+1):
if word[indx-1:indx] not in ['a','e','i','o','u']:
itr = indx
while itr < len(word)+1:
return_lst.append(word[indx-1:itr])
itr +=1
return return_lst
def vowelwordfinder(word):
word = word.lower()
return_lst = []
for indx in range(1,len(word)+1):
if word[indx-1:indx] in ['a','e','i','o','u']:
itr = indx
while itr < len(word)+1:
return_lst.append(word[indx-1:itr])
itr +=1
return return_lst
def game_scorer(const_list, vow_list):
if len(const_list) == len(vow_list):
return 'Draw'
else:
if len(const_list) > len(vow_list):
return 'Stuart ' + str(len(const_list))
else:
return 'Kevin ' + str(len(vow_list))
input_str = input()
print(game_scorer(constwordfinder(input_str), vowelwordfinder(input_str)))
This worked for smaller strings like BANANA, although when HackerRank started inputting strings like the following, I got multiple Runtime errors on the test cases:
NANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANANNANAN
I tried structuring the program to be a bit more concise, although I still got Runtime errors on the longer test cases:
def wordfinder(word):
word = word.lower()
return_lst = []
for indx in range(1,len(word)+1):
itr = indx
while itr < len(word)+1:
return_lst.append(word[indx-1:itr])
itr +=1
return return_lst
def game_scorer2(word_list):
kevin_score = 0
stuart_score = 0
for word in word_list:
if word[0:1] not in ['a','e','i','o','u']:
stuart_score += 1
else:
kevin_score +=1
if stuart_score == kevin_score:
return 'Draw'
else:
if stuart_score > kevin_score:
return 'Stuart ' + str(stuart_score)
else:
return 'Kevin ' + str(kevin_score)
print(game_scorer2(wordfinder(input())))
What else exactly should I be doing to structure my program to avoid Runtime errors like before?
Here's a quick and dirty partial solution based on my hints:
input_str = raw_input()
kevin = 0
for i, c in enumerate(input_str):
if c.lower() in "aeiou":
kevin += len(input_str) - i
print kevin
Basically, iterate over each character, and if it is in the set of vowels, Kevin's score increases by the number of remaining characters in the string.
The remaining work should be rather obvious, I hope!
[stolen from the spoilers section of the site in question]
Because say for each consonant, you can make n substrings beginning with that consanant. So for the BANANA example look at the first B. With that B, you can make: B, BA, BAN, BANA, BANAN, BANANA. That's six substrings starting with that B or length(string) - indexof(character), which means that B adds 6 to the score. So you go through the string, looking for each consonant, and add length(string) - index to the score.
The problem here is your algorithm.You are finding all the Sub strings of the text. It takes exponential time to solve the problem. That's why you got run time errors here. You have to use another good algorithm to solve this problem rather than using sub strings.
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