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})
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.
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))
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()
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