I am currently programming the Caesar Cipher.
I created a list of the alphabets
It simply asks for a sentence
Gets the index position of each letter in the sentence in corresponding to the alphabet list,
Adds the offset onto each offset using a while loop, creating a new index
Prints out the corresponding alphabet list index with new index which makes a coded word.
Therefore creating a coded sentence
The problem is that the alphabet list does not contain spaces, so I get an error when I try to make a sentence (because it is separated by spaces), only single words/letters work...
CODE HERE:
#Creating Lists
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"]
#Unpickling Dictionary
unpickle_codedwords = open("CWs.txt", "rb")
codedwords = pickle.load(unpickle_codedwords)
unpickle_codedwords.close()
###############################################################
""" #
IMPROVMENTS: #
Spaces/Sentences dont work <-- bob is a boy (ERROR) #
""" #
###############################################################
loop = 0#Using this to make my program loop continously
while loop == 0:
choice=int(input("What would you like to do?\n1)Code a word\n2)Decode a word\n3)Print the coded words list\n4)Quit the program\n5)Clear Coded Words List\n>>>"))#Asking for choice from user
if choice ==1:#If the choice selected was 1:
word=input("Enter the word you want to code\n>>>")
offset=int(input("Enter the offset below\n>>>"))
if word.isalpha() ==True:#checking alphabet only
for letter in word.lower(): # getting index of everysingle letter and converting it to lowercase
index=alphabet.index(letter)
index=index+offset#adding the index to the offset to create new index
while index>25:#if index is more than 25 i have to while loop it
index=index-26#creatingn the new index
codedwords.append([alphabet[index]])#appending each letter to word
#print(alphabet[index])<-- REMOVE LATER
answer = [''.join([x[0] for x in codedwords])] #instead of print(codedwords) because that prints[i],[i],[i] not iii
print(answer)
while word.isalpha()==False:#if word is not alphabeticals
print("Invalid Entry!, Please Try again\n")#loop it around again untill it's correct
word=input("Enter the word you want to code\n>>>")
if word.isalpha()==True:#looping round untill correct
for letter in word.lower():
index=alphabet.index(letter)
index=index+offset#Repeated again as above
while index>25:
index=index-26
codedwords.append([alphabet[index]])
answer = [''.join([x[0] for x in codedwords])]
print(answer)
You can use all to check if all letters in user input (word) are alpahanumeric or spaces:
while all(True if letter in alphabet + [' '] else False for letter in word):
>>> all([True, True])
True
>>> all([True, False])
False
>>>
After that:
for letter in word:
if letter == ' ':
codedwords.append([letter])
else:
# Code the letter
Related
this is my first post here so apologies for formatting in advance, I am trying to write a simple program in Python that takes a word, in this case, the word "ace" and checks all the possible words that can be generated by switching out the letter 'c' with all the letters in the alphabet. What I have tried is turning both my word and the alphabet into lists so I can and create some kind of loop that runs through all the possibilites and eventually cross references them with a dictionary of possible english words (haven't got there yet). I don't have strong a programming background so this has proven to be harder than I thought, my limited work is below, have been at this for a few hours, thanks!
My code...(it doesnt work at the moment)
#take letter ace and input new middle letter
word = list("ace")
alphabet = list("abcdefghijklmnopqrstuvwxyz")
wordnew = []
counter = 0
for word[1] in word:
wordnew = word.replace("c", alphabet[0] if counter < 25)
print(wordnew)
Note that you have to put a variable name to be created between the for and the in — word[1] is not a valid variable name, so your code should fail with a SyntaxError exception.
You can iterate over each letter of the alphabet and create a list of words generated from ace:
alphabet = "abcedfghijklmnopqrstuvwxyz"
words = []
for letter in alphabet:
words.append("ace".replace("c", letter))
You can even do this in one line, using a list comprehension:
words = [ "ace".replace("c", letter) for letter in "abcdefghijklmnopqrstuvwxyz" ]
Note how I didn't have to turn alphabet into a list—in Python, strings are iterable, meaning that you can loop through them just like you can with lists.
Of course, you can print them all, add this at the end:
print(words)
PS: You could also turn "abcdefghijklmnopqrstuvwxyz" into string.ascii_lowercase, though you'll have to import the string module (built into python).
You're close, here is a simple way to do it
>>> word = "ace" #no need to make it a list, you want it to be a string so you can use .replace on it
>>> alphabet = "abcdefghijklmnopqrstuvwxyz" #you can use string in a for loop, in which case they are treated like a list of characters
>>> for letter in alphabet:
print(word.replace("c",letter)) #here you do what you need, here I print it but you can save in a list by doing an .append into one or with a list comprehension which is the prefer mode to make list
aae
abe
ace
ade
aee
afe
age
ahe
aie
aje
ake
ale
ame
ane
aoe
ape
aqe
are
ase
ate
aue
ave
awe
axe
aye
aze
>>>
>>> wordnew = [word.replace("c",letter) for letter in alphabet] #the list comprehension version of the above
>>> wordnew
['aae', 'abe', 'ace', 'ade', 'aee', 'afe', 'age', 'ahe', 'aie', 'aje', 'ake', 'ale', 'ame', 'ane', 'aoe', 'ape', 'aqe', 'are', 'ase', 'ate', 'aue', 'ave', 'awe', 'axe', 'aye', 'aze']
>>>
word = 'ace'
alphabet = list("abcdefghijklmnopqrstuvwxyz")
for letter in alphabet:
print(word.replace('c', letter))
If you want the list of all possible "words" after replacement of letter "c" by any other letter from the alphabet you can simply do the following
word = "ace"
alphabet = "abcdefghijklmnopqrstuvwxyz"
new_words = [word.replace('c', ch) for ch in alphabet]
print(new_words)
word = "ace"
alphabet = list("abcdefghijklmnopqrstuvwxyz")
for letter in alphabet:
wordnew = word.replace("c", letter)
print(wordnew)
You should iterate through the alphabet, not the word.
Assuming you somehow have a list of all the words that exist, this works:
word = "ace"
alphabet = "abcdefghijklmnopqrstuvwxyz"
wordnew = []
counter = 0
# list full of all real words
legitWords = ['ace', 'man', 'math', 'marry' 'age',
'ape', 'are', 'ate', 'awe' 'axe']
for letter in alphabet: # looping through every letter in the alphabet
newWord = word.replace('c', letter) # replaces c with current letter
if newWord in legitWords:
# adds the counter and appends the new word, if it really exists
counter += 1
wordnew.append(newWord)
note that you don't have to convert the strings to lists as you have done, because they are iterable
.
I wish to write a hangman program and in order to do so, I have to replace the hash ('-') letter(s) with the user's guessed letter (guess). But when I run the code, it replaces all the hashes with the user's guess letter.
The code seems okay but I don't get the desired result.
words is a list of words I have written before the function.
def word_guess():
random.shuffle(words)
word = words[0]
words.pop(0)
print(word)
l_count = 0
for letter in word:
l_count += 1
# the hidden words are shown a '-'
blank = '-' * l_count
print(blank)
guess = input("please guess a letter ")
if guess in word:
# a list of the position of all the specified letters in the word
a = [i for i, letter in enumerate(word) if letter == guess]
for num in a:
blank_reformed = blank.replace(blank[num], guess)
print(blank_reformed)
word_guess()
e.g: when the word is 'funny', and guess is 'n', the output is 'nnnnn'.
How should I replace the desired hash string with guess letter?
it replaces all the hashes
This is exactly what blank.replace is supposed to do, though.
What you should do is replace that single character of the string. Since strings are immutable, you can't really do this. However, lists of strings are mutable, so you could do blank = ['-'] * l_count, which would be a list of dashes, and then modify blank[num]:
for num in a:
blank[num] = guess
print(blank)
A couple things to note:
inefficient/un-pythonic pop operation (see this)
l_count is just len(word)
un-pythonic, unreadable replacement
Instead, here's a better implementation:
def word_guess() -> str:
random.shuffle(words)
word = words.pop()
guess = input()
out = ''
for char in word:
if char == guess:
out.append(char)
else:
out.append('-')
return out
If you don't plan to use the locations of the correct guess later on, then you can simplify the last section of code:
word = 'hangman'
blank = '-------'
guess = 'a'
if guess in word:
blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
blank_reformed
'-a---a-'
(You still have some work to do make the overall game work...)
Was wondering how you would use a string that is equal to an interger as the integer in an index.
word = input("Enter word:")
print(word)
letterNum = int(len(word)) #determines amount of letters in word
print(letterNum)
lastLetter = word[letterNum] #supposed to figure out the last letter in a word
print(lastLetter)
This will get you the last letter in a word without all the code. I'm unsure what you're asking by index though.
word = input("Enter word: ")
print(word[-1])
Example:
Enter word: Test
#"t"
If you're asking if "Test 1" was input and you want to get the last character as a number then it's as simple as wrapping it in int but do some checking first.
word = input("Enter word: ")
last_char = word[-1]
if isnumeric(word[-1]):
print(int(last_char))
else:
print(last_char)
Examples:
Enter word: Test 1
#1
Enter word: Test
#"t"
The simplest way with python is to index using -1. Negative indexes count from the end of the string so word[-1] will always give you the last letter
Here I am giving you few of the examples including above.
word = input("Enter word:").strip() # strip() is used to remove any trailing or leading white spaces
print(word)
letterNum = int(len(word)) # Determines amount of letters in word
print(letterNum)
# 1st way (Using the internet that we created above)
lastLetter = word[letterNum - 1] # Supposed to figure out the last letter in a word
print(lastLetter)
# 2nd way (As the above answers suggest, -ve index, -1 for last, -2 for 2nd last, this is best, but this basically for Python, other language like C/C++ etc. use 1st way)
print(word[-1])
# 3rd way (Not good, but it is good for those who are learning Python,Reversing the string and printing 1st character)
print(word[::-1][0])
I'm writing a Hangman Program, and I'm basically done, I'm just stuck on one part. So you have to detect repetition in your input, i got that part done, but then i messes up with words that have the same letter in it.
For Example:
The Word is apple:
when I input a, it says well done, the letter is in the word and prints a----
but when I input p, it says well done as well but only prints the first p, so the output looks like this ap---
but i want it to detect all p in the word, for example : app--
here are my codes for that part:
def getGuessedWord():
position = word.index(letter.lower())
global words
words = words[:position] + letter.lower() + words[position+1:]
print(words)
return words
You need to find all the positions of the letter in your word!
Iterate through your word(enumerate function returns the list of index and value) and check if the value is the letter your are searching for!
Then
modify your words string!
That is
def getGuessedWord(letter,words,word):
for position, ltr in enumerate(word):
if ltr == letter:
words = words[:position] + letter.lower() + words[position+1:]
print(words)
return words
word='apple'
words='-'*len(word)
while '-' in words:
words = getGuessedWord(raw_input('Enter a letter : '),words,word)
Output:
Enter a letter : l
---l-
Enter a letter : e
---le
Enter a letter : a
a--le
Enter a letter : p
apple
Hope it helps!
Given, for example:
letter = 'p'
word = 'apple'
With this list comprehension:
[x==letter for x in word]
You can detect where is a certain letter is, if it is at all, in this example it would return:
[False, True, True, False, False]
Which corresponds with the fact that only the second and third letters in apple are "p".
Because True is 1 in Python, the same happens with 0 and False. So, if you want a numeric value you can just sum the values in the list, by doing:
sum([x==letter for x in word])
You could try this to verify the previous statement:
>>> True == 1
True
>>> False == 0
True
For a more detailed/specific answer, I'll need more information about how it is implemented.
For an assignment, I need to use a while loop to reverse a list, and I just can't do it.
This is the sample code I have to help me get started:
sentence = raw_int (" ")
length = len(sentence) # determines the length of the sentence (how many characters there are)
index = length - 1 #subtracts one from the length because we will be using indexes which start at zero rather than 1 like len
while... #while the index is greater than or equal to zero continue the loop
letter = sentence[index] #take the number from the index in the sentence and assigns it to the variable letter
I need to use this in my solution.
sentence = raw_input(" ")
length = len(sentence)
index = length - 1
reversed_sentence = ''
while index >= 0:
#letter is the last letter of the original sentence
letter = sentence[index]
#make the first letter of the new sentence the last letter of the old sentence
reversed_sentence += letter
#update the index so it now points to the second to last letter of the original sentence
index = index - 1
print reversed_sentence
Because this is an assignment, I'm not going to give you the full code. But I will give you two 'hints'.
1) a sentenced is reversed if every character is 'flipped'. For example, 'I ran fast'-to flip this sentence first swap 'I' and 'f', then space and 's' and so on.
2) you can use syntax like:
Sentence[i], sentence[len(sentence)-i] = sentence[len(sentence)-i], Sentence[i]
This should definitely be enough to get you going.
You can do:
new_sentence = list()
sentence = list(raw_input(" "))
while sentence:
new_sentence.append(sentence.pop(-1))
else:
sentence = ''.join(new_sentence)