I'm trying to see if a word or sentence has each letter of the alphabet and I can't get it to print all the letters that isn't in the sentence/word.
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'
,'u','v','w','x','y','z']
x = raw_input('')
counter = 0
counter2 = 0
for i in range(len(x))
counter += 1
for o in range(26):
counter2 += 1
if alpha[counter2] not in x[counter]:
and I'm stuck there...
alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'
,'u','v','w','x','y','z'}
input_chars = set(raw_input())
print alphabet - input_chars
All we do is set difference between the set of alphabet characters and the set of characters in our input. Note that the difference operation can take as a second operand any iterable, so we don't even really have to turn our input into a set if we don't want to, although this will speed up the difference a small amount. Furthermore, there is a built-in string which gives us the ascii letters so we could do it like this:
import string
print set(string.ascii_lowercase) - raw_input()
using set difference:
import string
x=raw_input()
not_found=set(string.ascii_lowercase) - set("".join(x.split()))
print (list(not_found))
output:
>>>
the quick brown fox
['a', 'd', 'g', 'j', 'm', 'l', 'p', 's', 'v', 'y', 'z']
Since you're already iterating over both strings, there is no need to use counter and counter2.
You were almost there. Python makes list operations simple, so there's no need to iterate over the lists element-by-element using indices:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
sentence = raw_input('Enter a sentence: ').lower() # Because 'a' != 'A'
letters = []
for letter in sentence:
if letter in alphabet and letter not in letters:
letters.append(letter)
print(letters)
Much easier:
import string
x = raw_input()
print [c for c in string.ascii_lowercase if c not in x]
Related
As my first personal project I am building a Wordle "solver" that comes up with a first guess word then takes an input of the letters that were correct in the word then searches the word list for words with similar characters. To do this I stored each word in a dictionary with the key being the word and the value being each character in the word i.e dodge: [d, o, d, g, e]. I am currently experimenting to get code running that parses through the values of the dictionary to match the characters to the inputted letters but am stumped on how to search through the lists within the dictionary as a loop.
Here's my code for inputting the correct letters:
correct_letters_1 = list(letters for letters in input("Input corrects letters: ").strip().split())
Here's one of my attempts at parsing the dictionary:
for letters in correct_letters_1:
if letters in word_dictionary.values():
print("yes")
I'm pretty sure this problem has something to do with my code parsing the entire lists within the dictionary rather than each individual character but even when I try inputting the whole word, i.e Input Correct Letters: d o d g e; I still don't have any output.
If someone could put a beginner on the right track it would be much appreciated.
You might be looking to compare the whole list, rather than the letters:
correct_letters_1 = list(input("Enter correct letters: ").strip())
# correct_letters_1 is a whole list
if correct_letters_1 in word_dictionary.values():
print("yes")
# Inputting "abc"
>>> correct_letters_1
['a', 'b', 'c']
>>> word_dictionary
{'abc': ['a', 'b', 'c']}
>>> correct_letters_1 in word_dictionary.values()
True
To check if the user's guess is a subset of any of the words:
correct_letters_1 = list(input("Enter correct letters: ").strip())
let_set = set(correct_letters_1)
word_dictionary = {'abc': ['a', 'b', 'c'],
'abcde': ['a', 'b', 'c', 'd', 'e'],
'ab': ['a', 'b'],
'test': ['t', 'e', 's', 't']}
# Check to see if correct_letters_1 is a subset of any word in the dictionary
close_words = ["".join(x) for x in word_dictionary.values() if let_set <= set(x)]
Which can be simplified to:
correct_letters_1 = input("Enter correct letters: ").strip()
let_set = set(correct_letters_1)
words = ["abc", "test", "ab"]
# Check to see if correct_letters_1 is a subset of any word in the list words
close_words = [x for x in words if let_set <= set(x)]
I'm trying to reverse a string, so I converted the string into a list and was trying to send the last element to the front, 2nd to last element to the 2nd space, etc.
word = input("Enter a word: ")
word = list(word)
count = 0
while count < len(word):
word.insert(count, word.pop())
count = count + 1
print(word)
It just returns the original string in list form, even though I'm saving the last letter and inserting it before popping it off of the string? Does word.pop() not capture the last letter of a string before deleting it or am I overlooking something?
Well the simplest way to do what you are trying is to slice the string in reverse order, this does not even require changing into a list:
word = input("Enter a word: ")
return word[::-1]
Here's an experiment:
>>> word = list('python')
>>> word.insert(0, word[-1])
>>> word
['n', 'p', 'y', 't', 'h', 'o', 'n']
>>> word.remove(word[-1])
>>> word
['p', 'y', 't', 'h', 'o', 'n']
Wait, what?!
>>> help(word.remove)
Help on built-in function remove:
remove(value, /) method of builtins.list instance
Remove first occurrence of value.
Raises ValueError if the value is not present.
Remove first occurrence of value.
So, you inserted word[-1] at the beginning of the list, and then word.remove immediately removes the first occurrence of word[-1], which is now at the beginning of the list, you've just inserted it there!
You're setting the variables inside the while-loop to the same value. Also, use list.pop to remove the element from the list. For example:
word = input("Enter a word: ")
word = list(word)
count = 0
while count < len(word):
word.insert(count, word.pop())
count = count + 1
print(word)
Prints:
Enter a word: book
['k', 'o', 'o', 'b']
Here is the docstring for list.remove:
>>> help(list.remove)
Help on method_descriptor:
remove(self, value, /)
Remove first occurrence of value.
Raises ValueError if the value is not present.
>>>
As you can see, list.remove removes the first occurrence of the given value from the list. All your backwards function does right now is take the last character of the word, add it to the front and then immediately remove it from the front again. You do this once for every character in the word, the net result being no change.
I am doing this code wars kata https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/python
you have to return the highest scoring word within a string. letters are scored based on position in the alphabet
a =1, z= 26
I've created a list :
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
I want to iterate through the words, which will be in the string (x) passed as a parameter, and if the letter being checked is in the alphabet list, which it of course will be, then to a sperate variable: score, increment score by the number at which the current letter being checked is indexed within the alphabet list.
Is it possible to use list indexes in this way?
Here's my code soo far:
def high(x):
alphabet = []
scores = [] # ignore
score = 0
for letter in range(97,123):
alphabet.append(chr(letter))
word_list = x.split()
for word in word_list:
for letter in word:
if letter in alphabet:
score += # find way to use alphabet list index number as integer here
Thanks.
From what I can see the list of letters isn't needed at all :
import string
def high(x):
score = 0
for word in x.split():
for letter in word:
if letter in string.ascii_lowercase:
score += ord(letter)-96
return score
or even simpler :
import string
def high(x):
# Sum expression on multiple lines for clarity
return sum( ord(letter)-96
for word in x.split()
for letter in word
if letter in string.ascii_lowercase)
Use list comprehensions and dictionary score to keep track of each letter and its score. Notice that the input string is lowercased - I assume that upper- and lowercase letters are scored the same.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
score = dict(zip(list(alphabet), [i + 1 for i in range(len(alphabet))]))
x = 'aB, c'
score = sum([score[c] for c in list(x.lower()) if c in score])
print(score)
# 6
#AlanJP, would you like to try this program:
# simple word scoring program
import string
characters = string.ascii_lowercase
ranking = {c: i for i, c in enumerate(characters, 1)}
#print(ranking)
word_list = 'abba is great'.split()
for word in word_list:
score = 0 # reset the score for each incoming word
for char in word:
score += ranking[char]
print(word, score)
Output:
abba 6
is 28
great 51
>>>
Yes. alphabet.index(letter) + 1 will give you what you want.
index() you're going also want to +1 to account for index [0]
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
Write a program that receives a string and shifts all the vowels present in it to the beginning.
I have tried sorting the vowels one by one and removing them on the go and saving the two strings separately,then at the end i joined it
s = "You love Python!"
vowels = "aeiou"
s1= ""
for l in range(0,len(s)):
if s[l] in vowels:
s1 = s1+s[l]
s2 = s.replace(s[l],"")
print(s1+s2)
OUTPUT :
ouoeoYu lve Pythn!
But in output "e" in second word is not sorted. What is the error?
Problem:
The reason your code does not quite work is because you sometimes use s and sometimes s2. s.replace(s[l],"") does nothing to s - so every time you use it, s2 gets to be s with one vowel replaced in it - the others vowels are taken as isfor s.
The last vowel replaced is o - so s2 becomes: Yu lve Pythn! - u and e are still in it.
Your code fixed:
s = "You love Python!"
vowels = "aeiou"
s1 = ""
for c in s:
if c in vowels:
s1 = s1+c # produces new string every time
s = s.replace(c,"") # produces new string every time
print(s1+s) # ouoeoY lv Pythn!
Optimizations:
Do not iterate by index, iterate over the characters of a string directly. If you collect things from strings, avoid producing more strings, use a list instead. Strings are immuteable, every time you modify one it is constructed new.
Suboptimal:
You can use list comprehensions to get the chars into two lists, combine both lists and join them back into a string:
s = "You love Python!"
s1 = [x for x in s if x.lower() in "aeiou"] # gets vowels, order and capitalization is kept
s2 = [x for x in s if x.lower() not in "aeiou"] # gets all other characters
s3 = ''.join(s1+s2) # adds lists back together and makes it a continious string
print(s1)
print(s2)
print(s3)
Output:
['o', 'u', 'o', 'e', 'o']
['Y', ' ', 'l', 'v', ' ', 'P', 'y', 't', 'h', 'n', '!']
ouoeoY lv Pythn!
Disadvantage: you have to go over the whole string twice. A simple for loop can do it in one pass:
s = "You love Python!"
s1=[]
s2=[]
for c in s:
if c in "aeiou":
s1.append(c)
else:
s2.append(c)
s3 = ''.join(s1+s2)
print(s1)
print(s2)
print(s3)
Output is the same.
Doku:
python list comprehension
Does Python have a ternary conditional operator?
str.join( iterable )
s = "You love Python"
vowels = 'aeiouAEIOU'
v = ""
c = ""
for i in s:
if i in vowels:
v = v+i
else:
c= c+i
final_string = v+c
print(final_string)
Define a function named encrypt which takes as input a string (which is the name of a text file in the current directory). The function should then print the encrypted content of this file.
Here text encryption is done by replacing every occurence of a vowel with its next in the list 'aeiou'. So 'a' is replaced by 'e', 'e' is replaced by 'i', so on and 'u' is replaced by 'a'. Also each consonant is replaced with its next in the list 'bcdfghjklmnpqrstvwxyz' so 'b' is replaced by 'c', 'c' by 'd' so on and lastly 'z' is replaced by 'b'. The same replacement logic holds for upper case letters. Note that non-alphabetic characters should appear in their original form without modification.
def encrypt (eo):
vowel = 'aeiou'
con = 'bcdfghjklmnpqrstvwxyz'
for eo in vowel (t[i+1]):
res=
return res
This piece of code could be useful. Pay attention to the vowel and con content. I appended one letter in each variable vowel and com to avoid the modulo operation. Assume the eo is the input string.
def encrypt (eo):
vowel = 'aeioua'
con = 'bcdfghjklmnpqrstvwxyzb'
encrytTable = vowel + con
res = ""
for letter in eo:
res += encrytTable[encrytTable.find(letter)+1]
return res
If eo is the input filename, you need some file read operation like:
>>> fh = open(eo)
>>> fh.read()
>>> fh.>>> fh.close()
And a more effient way to do it, is pre-compute a encryptTable array and use the table to replace the origianl input in a linear manner. In following code, I assume your input only include lower-case letters. Abd if the shift distance is not 1, you need to modify the code. Pre-compute:
>>> vowel = 'aeioua'
>>> con = 'bcdfghjklmnpqrstvwxyzb'
>>> encryptTable = []
>>> for i in xrange(97,123):
temp = chr(i)
if temp in vowel:
encryptTable.append(vowel[vowel.find(temp)+1])
else:
encryptTable.append(con[con.find(temp)+1])
>>> encryptTable
['e', 'c', 'd', 'f', 'i', 'g', 'h', 'j', 'o', 'k', 'l', 'm', 'n', 'p', 'u', 'q', 'r', 's', 't', 'v', 'a', 'w', 'x', 'y', 'z', 'b']
And then replace the content:
>>> plain = "helloworld"
>>> encrypted = "".join([encryptTable[ord(i)-ord('a')] for i in plain])
>>> encrypted
'jimmuxusmf'
def encrypt(s):
vowels = 'aeiou'
vowelReps = dict(zip(vowels, vowels[1:]+vowels[0]))
cons = 'bcdfghjklmnpqrstvwxyz'
consReps = dict(zip(cons, cons[1:]+cons[0]))
answer = []
for char in s:
if char.lower() in vowelReps:
answer.append(vowelReps[char.lower()]
else:
answer.append(consReps[char.lower()]
if char.isupper():
answer[-1] = answer[-1].upper()
return ''.join(answer)
You have multiple problems here:
for eo in ... would replace the eo argument; except
t isn't defined, so will give a NameError;
res= is a SyntaxError; and
Even if all of the above was fixed, return res will happen on the first character, as it is indented too far.
Instead, you could do the following:
def encrypt(eo):
vowels = "aeiou"
for index, vowel in enumerate(vowels): # iterate through the five vowels
new_v = vowels[(index + 1) % len(vowels)] # determine replacement
eo = eo.replace(vowel, new_v) # do replacement
You can then do the same thing for the consonants, then return eo (which should be indented to the same level as vowels = ...!).
Note:
the use of % to keep the index into vowels within the appropriate range; and
the use of enumerate to get both the character vowel from the string vowels and its index within that string.
Alternatively, and more efficiently:
build a dictionary mapping character in to character out;
build a list of replacement characters using the input eo and the dict; and
str.join the output characters together and return it.