Python boggle game - python

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

Related

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.

minion game substrings off-by-one

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.

Python While Loop: Else tripped despite valid input

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.

Can you search for how many times a words occurance appears in a sentence and give both positions of the words?

I have been trying to find a single word in a sentence and show its position. with the following:
sentence= input("Write a sentence with two words the same: ")
findme = input("Type a word that appears twice: ")
words = sentence.split()
print (list(enumerate(words)))
print ("The length of sentnce in chracters is",len(sentence))
t = words
print("third word in sentence is:", t[2])
if sentence.find(findme)!=-1:
print("found word")
else:
print("word not found")
print (sentence.find(findme))
numberofwords = len(t)
print("The amount of words in the sentence is:",numberofwords,"words.")
print("This is the last time",findme,"is found in the sentence, its at",sentence.rfind(findme))
print (sentence.index(findme))
test_words = sentence.split()
position = test_words.index(findme)
position = position +1
if position == 1:
addtoword = "st"
elif position == 2:
addtoword = "nd"
elif position == 3:
addtoword = "rd"
elif position >=4:
addtoword = "th"
print ("The word",findme,"is the",position,addtoword,"and position",position,"word in the sentence.")
print ("The word",findme,"appears",sentence.count(findme),"times in the sentence provided.")
But I want to simplify and display the location of the repeated word for example
in " The cat sat on the mat with another cat." would return " The word Cat occurs 2 times, once at 2nd position then at 9th position.
Using collection's Counter
from collections import Counter
sent = "The cat sat on the mat with another cat."
# lower the sentence, strip it from punctuation and split
l = sent.lower().strip('?!.,').split()
# create Counter and find most common word
word = Counter(l).most_common(1)[0][0] # 'the'
# find positions with the word
indices = [i for i, x in enumerate(l) if x == word] # [0, 4]
As #jonrsharpe suggested, you can store all of the locations in a list and then get the first two elements.
Here is your code again, with the parts I've added commented to explain what they do:
sentence= input("Write a sentence with two words the same: ")
findme = input("Type a word that appears twice: ")
words = sentence.split()
print (list(enumerate(words)))
print ("The length of the sentence in chracters is",len(sentence))
t = words
print("third word in sentence is:", t[2])
if sentence.find(findme)!=-1:
print("found word")
else:
print("word not found")
print (sentence.find(findme))
numberofwords = len(t)
print("The amount of words in the sentence is:",numberofwords,"words.")
print("This is the last time",findme,"is found in the sentence, its at",sentence.rfind(findme))
print (sentence.index(findme))
# Set up the variables we will need
lastFoundIndex = 0 # last position we found the word at
test_words = sentence.split() # List of words
positions = list() # list of positions
while lastFoundIndex < len(test_words):
try: # try will try the code found in the block.
foundPosition = test_words.index(findme, lastFoundIndex)
except ValueError: # except catches errors from try, and then runs the code in it's block.
# In this case, if a ValueError is returned when we run the code in the try block,
# we break out of the loop.
break;
finally: # finally is executed after try and any corresponding excepts.
positions.append(foundPosition) # It adds the found position to the list of positions...
lastFoundIndex = foundPosition + 1 # and increases the lastFoundIndex.
# The +1 is needed so it doesn't constantly find the word we just found.
# Replace everything after this point if you want all the positions
position1 = positions[0] + 1 # Get the positions of the first two occurrences...
position2 = positions[1] + 1 # ...and add 1 to them so they work with the code.
if position1 == 1:
addtoword1 = "st"
elif position1 == 2:
addtoword1 = "nd"
elif position1 == 3:
addtoword1 = "rd"
elif position1 >=4:
addtoword1 = "th"
if position2 == 1:
addtoword2 = "st"
elif position2 == 2:
addtoword2 = "nd"
elif position2 == 3:
addtoword2 = "rd"
elif position2 >=4:
addtoword2 = "th"
print ("The word",findme,"is the",position1,addtoword1,"and",position2,addtoword2,"position word in the sentence.")
print ("The word",findme,"appears",len(positions),"times in the sentence provided.")
Keep in mind that it only shows the positions for the first and second occurences of the word. If you want all of them, replace the code after the commented point that says Replace everything after this point if you want all the positions with this:
print("The word",findme,"is the ", end='') # end='' means that it doesn't end with a newline
wordingIndex = 1 # What item of the list we are on. Used for wording purposes
for position in positions: # Loop through all the elements
position = position + 1
if position == 1:
addtoword = "st"
elif position == 2:
addtoword = "nd"
elif position == 3:
addtoword = "rd"
else:
addtoword = "th"
# Now we word the sentence properly.
if wordingIndex == len(positions): # If we're at the final position, don't add a comma
print(position, addtoword, end='', sep='') # sep is the separator between words. It defaults to a space (' '), but
# setting it to '' will make the text appear as "1st" rather than "1 st".
elif wordingIndex == len(positions) - 1: # If we're at the second-to-last position, add an and
print(position, addtoword, ' and ', end='', sep='') # Keep in mind when using sep='', you have to add spaces between words and variables,
# or you'd get "1stand".
else: # If we're anywhere else, just add a comma
print(position, addtoword, ', ', end='', sep='')
wordingIndex = wordingIndex + 1 # Increment the wording counter
print(" word(s) in the sentence provided.")
print ("The word",findme,"appears",len(positions),"times in the sentence provided.")
Also keep in mind Python requires proper indentation. So this is valid code:
if (someVariable == 1):
print("That variable equals one!")
but this isn't:
if (someVariable == 1):
print("That variable equals one!") # Will not run due to indentation errors
Note that the first example will not work if there are less than two instances of the word.

In python, how do I find the vowels in a word?

I am trying to make an up language translator. Simple task for me in python. Or so i thought. If you are unaware, up language is when you take a word and say it while adding up before every vowel. for example, Andrew would be Upandrupew. I am trying to find out how find all of the vowels in a user submitted word, and put up before them. Is there a way to cut up a word before all vowels. so excellent would be exc ell ent? thanks.
maybe
VOWELS = 'aeiou'
def up_it(word):
letters = []
for letter in word:
if letter.lower() in VOWELS:
letters.append('Up')
letters.append(letter)
return ''.join(letters)
can be simplified to
def up_it(word):
return ''.join('up'+c if c.lower() in 'aeiou' else c for c in word)
You could do that with a regex:
import re
a = "Hello World."
b = re.sub("(?i)([aeiou])", "up\\1", a)
The (?i) makes it case-insensitive. \\1 refers to the character that was matched inside ([aeiou]).
''.join(['up' + v if v.lower() in 'aeiou' else v for v in phrase])
for vowel in [“a“,“e“,“i“,“o“,“u“]:
Word = Word.replace(vowel,“up“+vowel)
print(Word)
import re
sentence = "whatever"
q = re.sub(r"([aieou])", r"up\1", sentence, flags=re.I)
vowels = ['a', 'e', 'i', 'o', 'u']
def upped_word(word):
output = ''
for character in word:
if character.lower() in vowels:
output += "up"
output += character
return output
Here is a one-liner for the entire problem
>>> "".join(('up' + x if x.upper() in 'AEIOU' else x for x in 'andrew'))
'upandrupew'
Here's one way of doing it.
wordList = list(string.lower())
wordList2 = []
for letter in wordList:
if letter in 'aeiou':
upLetter = "up" + letter
wordList2.append(upLetter)
else:
wordList2.append(letter)
"".join(wordList2)
Create a list of letters (wordList), iterate through those letters and append it to a second list, which is joined at the end.
Returns:
10: 'upandrupew'
In one line:
"".join(list("up"+letter if letter in "aeiou" else letter for letter in list(string.lower())))
I'd probably go with RegExp but there are already many answers using it. My second choice is the map function, witch is better then iterate through every letter.
>>> vowels = 'aeiou'
>>> text = 'this is a test'
>>> ''.join(map(lambda x: 'up%s'%x if x in vowels else x, text))
'thupis upis upa tupest'
>>>
def is_vowel(word):
''' Check if `word` is vowel, returns bool. '''
# Split word in two equals parts
if len(word) % 2 == 0:
parts = [word[0:len(word)/2], word[len(word)/2:]]
else:
parts = [word[0:len(word)/2], word[(len(word)/2)+1:]]
# Check if first part and reverse second part are same.
if parts[0] == parts[1][::-1]:
return True
else:
return False
This is a smart solution which helps you to count and find vowels in input string:
name = input("Name:- ")
counter = []
list(name)
for i in name: #It will check every alphabet in your string
if i in ['a','e','i','o','u']: # Math vowels to your string
print(i," This is a vowel")
counter.append(i) # If he finds vowels then he adds that vowel in empty counter
else:
print(i)
print("\n")
print("Total no of words in your name ")
print(len(name))
print("Total no of vowels in your name ")
print(len(counter))

Categories

Resources