I have a program where I need to prompt the user for an input of a word and a key. Next, the program should remove all the spaces, punctuation and all numbers from the word and convert all the letters into uppercase. Once that is done I need the program to replace all the characters of the word with the key. So if the word is a library, and the key is moose, the program should print out moosemo. I know that this part includes something like append.key(len plaintext) something of this fashion, but I'm not exactly sure how. I don't have a lot of the code done because I am pretty lost. Here is what I have so far:
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
print(phrase.upper()) #converts all characters from phrase to uppercase
If anyone knows what to do or what to change, please let me know. Please show the change in code with your response. Thanks in advance
I used answers from here and here to make compose this.
Here is one way you might do it, using the string class to get rid of punctuation and numbers.
import string
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
#replace - gets rid of spaces
#first translate - gets rid of punctuation
#second translate - gets rid of digits
#upper - capitalizes.
phrase = phrase.replace(" ", "")\
.translate(str.maketrans('', '', string.punctuation))\
.translate(str.maketrans('','',string.digits))\
.upper()
times_to_repeat = len(phrase)//len(encryptionkey)
leftover_length = len(phrase)%len(encryptionkey)
#multiply string by how many times longer it is than the encryption, then add remaining length.
#in python you can do 'string'*2 to get 'stringstring'
final_phrase = encryptionkey*times_to_repeat+encryptionkey[:leftover_length]
print(final_phrase)
Output:
# Only keep the alphabet characters
phrase = ''.join(c for c in phrase if c.isalpha())
# Add the encryption key at least 1 more times than divisible (to count for remainder)
# and slice the output to the length needed
phrase = (encryptionkey * (1 + len(phrase) // len(encryptionkey)) [:len(phrase)]
Related
In my program, the user can input a list of words or the letter n. What I want to do is when they input n, it want it to set the value of the variable where the user input is saved to a question mark (?).
Also in my program, the user inputs a different list, if they input n, I want the program to generate a word frequency table.
The problem I'm having is that when I write out the if statements for if the user input is n, I don't think that it's changing the value or creating the frequency table.
I've shifted where the code is in the program. I'm not getting the response from either if statement no matter where I put it in the code. Originally I thought the program was that I had put it near the end of the program and since it was reading it top to bottom, nothing was happening. Now, I'm not sure.
I've included the pieces of the code that would work together so I'm not pasting the entire program.
# Ask user for needed keywords or symbols
user_keywords = input("What keywords or special symbols would you like to search the provided file for?\n"
"Please separate each entry with a comma.\n If you would like to just search for question marks"
"please just type n.")
# Holding list, using comma as a way to separate the given words and symbols
list1 = list(user_keywords.split(','))
# Print list for user to see
print("You have entered the following keywords and/or special symbols: ", list1)
# Ask user for needed repeating words
user_repeating = input("What repeating words would you like to search the provided file for?\n"
"Please separate each entry with a comma. \n If you would like a frequency table for all words"
"two letters or more, please type n.")
# Holding list, using comma as a way to separate the given words and symbols
list2 = list(user_repeating.split(','))
# Print list for user to see
print("You have entered the following words: ", list2)
frequency = {}
# Check to see if list1 has no parameters and sets to ?
if list1 == 'n':
list1 = '?'
print("We will search for any question marks.")
# Check to see if list2 has no parameters and creates a frequency array
if list2 == 'n':
document_text = open (path1, 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{2-20}\b', text_string)
print("We will look for all word frequencies.")
for word in match_pattern:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
print(words, frequency[words])
I expect list1 to be set to ? when n is entered by the user. I expect list2 to generate a word frequency table when n is entered by the user.
I'm not getting any errors. At this point is just goes straight to the end of the program and returns the final print line I have in it, so I know it isn't calling the if statements.
Surely the way to do this is to replace:
list1 = list(user_keywords.split(','))
with
list1 = '?' if user_input == 'n' else list(user_keywords.split(','))
no?
I'm trying to a hangman game. I already achieved to set the basics of the game (list, interaction with user) but I don't know how to do the lines for the game, keep asking and printing what the user correct answers are and ilustrate the hangman.
I used index in order to search the exact location of the letter in the word, but I dont know to print it, depending on the number and also I don't how to code that the program keeps track of the correct words.
I would be totally glad for your help. Also thanks for your patience.
The first part of the code is well coded but stackoverflow doesn't display it right.
------------------------------------------------------------------------
import random
def hangman():
words = ['house','car','women', 'university','mother', 'school', 'computer','pants'] #list of words
computer = words[random.randint(0,6)] #computerchoice
word = list(computer) #Make a list with each letter of the word.
welcome = (input ('Welcome, type ok to continue: '))
if welcome == 'ok':
length = len(word)
print(f'help? the word has {length} letters')
option = (input('Start guessing, letter by letter'))
count= 0 #count takes the count of how many tries.
chances = length+3 #You are able to make 3 mistakes.
while count<=chances:
if option in word: #if the choice is there
place = word.index(option) #search for the place.
print() #dont know how to print it in 'that' place.
#place the correct letter over that line.
print('_ '*length) #Trying to do the under lines.
count+=1
else:
break
#Dont know to ilustrate the hangman depending on the length of the word.
hangman()
First let's analyse your code:
import random
def hangman():
words = ['house','car','women', 'university','mother', 'school','computer','pants'] #list of words
computer = words[random.randint(0,6)] #computerchoice
word = list(computer) #Make a list with each letter of the word.
Everything is fine up to here , although str can be used the same way as a list , so no need to transform it.
welcome = (input ('Welcome, type ok to continue: '))
if welcome == 'ok':
length = len(word)
print(f'help? the word has {length} letters')
Yes but those are not unique letters. You can use set() to have the number of unique letters.
option = (input('Start guessing, letter by letter'))
If your input starts here, you will only ask once for a letter , you need to include this part in the while loop
count= 0 #count takes the count of how many tries.
chances = length+3 #You are able to make 3 mistakes.
This would then probably be changed to the length of the set.
while count<=chances:
if option in word: #if the choice is there
place = word.index(option) #search for the place.
This will only give you the index of the first occurence.
We should keep in mind to use regex for this type of search : Find all occurrences of a substring in Python
print() #dont know how to print it in 'that' place.
Let's remember to use the print formating f'stufff{value}stuffff'
#place the correct letter over that line.
To do it , you need to create a str only with _and then fill it in with the indexes using list comprehension .
print('_ '*length) #Trying to do the under lines.
count+=1
Maybe we should handle what happens if option is not in words ?
else:
break
#Dont know to ilustrate the hangman depending on the length of the word.
Also there is no need for break : count increments and therefore while will terminate. And if it was for the outer if/else , break doesn't work outside a loop.
hangman()
Question for OP:
What point would you like to sort out yourself ? What do you need help for next ?
I am learning python, I used the the switcher dictionary. I encountered the problem of all the functions of the dictionary getting executed.
'''
Created on Mar 10, 2019
#author: priti
Questions
1) Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
2) Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
3) (HINT use re i.e. import re (re is regular expression library/functions).
Question:
A website requires the users to input username and password to register. Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$##]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
Example
If the following passwords are given as input to the program:
ABd1234#1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234#1
'''
# method used to perform operation regarding the first question
from unittest.util import sorted_list_difference
import re
def comma_separated():
sorted_list=[]
rawData = input("Please enter comma separated words\n")
rawData = rawData.strip().split(",")
for item in rawData:
item.strip()
sorted_list.append(item)
sorted_list.sort()
for item in sorted_list:
print(item)
def cal_num_upper_lower():
upperCase = 0
lowerCase = 0
rawData = input("Please enter string\n")
rawData.strip().split(",")
for i in rawData:
#print(i)
if(i.islower()):
lowerCase +=1
if(i.isupper()):
upperCase +=1
print("UPPER CASE = " + str(upperCase))
print("LOWER CASE = " + str(lowerCase))
# method used to perform operation regarding the third question
def check_regular_expression():
sorted_list=[]
password = input("Enter string to test: ")
password = password.strip().split(",")
for item in password:
item.strip()
sorted_list.append(item)
#
# print("match")
for item in sorted_list:
if(re.match(r"^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[##$]){6,12}", item)):
print(item)
def choose_the_option(argument):
switcher = {
1: lambda: comma_separated(),
2: lambda: cal_num_upper_lower(),
3: lambda: check_regular_expression(),
}
return switcher.get(argument,lambda: "Please enter a valid number") ()
print("Select one of the options")
option = int(input("1:Sort sequence of words\n2:Calculate Number of upper and lower case\n3:Check Regular Expression\n Please enter:"))
choose_the_option(option)
So I followed this question
Executing functions within switch dictionary
Here is is mentioned that we need to use lambda to ensure only the correct method is called. While the solution worked perfectly,I could not get what exactly happens when we use lambda in switcher.
Thanks.
I have recently started to learn python as I wanna enter a deep learning field in future.
As I'm completely new and only started I apologize in advance if my question is silly.
I am currently doing a course on edx by name introduction to python fundamentals and as I final project of module 1 I need to make a program that asks for user input and give an output of all words that starts from h to z.
task
here is my code:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
new_name = ""
for letter in user_input:
if letter.isalpha() == True:
new_name += letter.upper()
elif letter.isalpha() == False:
if new_name[0] > "g":
print(new_name)
new_name = ""
else:
new_name = "\n"
print(new_name)
INPUT = Wheresoever you go, go with all your heart
OUTPUT = WHERESOEVERYOUGOGOWITHALLYOURHEART
By my understanding of code I have wrote:
- user enters input
- code check for each character
- if letter is alpha that letter is added into new_name variable
- when encounter first no alpha character in these case space after word Wheresoever code moves to elif since after checking a fist one it was not True and elif turn to mach criteria
- then by using nested if statement it checks if new_name variable[index0] (Wheresoever) is grater then g.
- if it is grater it prints new_name and makes new_name empty and repeat the circle until there is no more characters to check.
- if its not greater then g it starts with new word on the new line
Now as I sad I'm completely new so I have just described my thoughts process of the code and please tell me where am I wrong and how can I corrected and improve my thoughts process and the code mentioned above.
Thank you in advance :)
Try the below, iterate trough the list split of the user_input string, then check if it starts with a G or g, if it does, don't keep it, otherwise keep it, then use regular expressions (re) to get only letters.
Also as you said you need isalpha so then:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
print('\n'.join([''.join(x for x in i if x.isalpha()).upper() for i in user_input.split() if not i.lower().startswith('g')]))
Example output:
enter a 1 sentence quote, non-alpha separate words: Wheresoever you go, go with your heart
WHERESOEVER
YOU
WITH
YOUR
HEART
Update form #KillPinguin:
do:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
print('\n'.join([''.join(x for x in i if x.isalpha()).upper() for i in user_input.split() if ord(i[0])>ord('g')]))
The purpose of my code it to intake a string from a user and turn into a non case-sensitive list. Then I need to intake a second string from the user then output the position of the second given string. This is my code:
UserSentence = input('Enter your chosen sentence: ') #this is where the user inputs their sentence
from string import punctuation #this 'fetches' the punctuation from the string
tbl=str.maketrans({ord(ch):" " for ch in punctuation})
UserSentence = UserSentence.lower().translate(tbl).split()#.split() turns the input sentence into a list,...
#...this will help to identify where a word appears...
#...in the sentence. The .lower() also turns the...
#...string into lowercase so it is not case sensitive.
UserWord = input('Enter a word from the sentence: ')#this is where the user inputs their word from the sentence
UserWord = UserWord.lower()#.lower() is used to make UserWord not case sensitive
for i in range(len(UserSentence)):
if UserSentence (i) == UserWord:
print ('Your chosen word appears in: ')
To index a sequence you need to use []
if UserSentence[i] == UserWord:
If you are trying to find which index (by word) their word is you can do
if UserWord in UserSentence:
print('Your word is located at {}'.format(UserSentence.index(UserWord)))
Or similarly
try:
print('Your word is located at {}'.format(UserSentence.index(UserWord)))
except ValueError:
print('Your word is not in the sentence')
Couple of errors here:
If you're using Python 2, use raw_input for strings. In Python 3 input is okay.
Your maketrans call is weird
For looking up if a word is inside a list you don't any loops or own comparisons. Python can do that for you.
Please stick to PEP0008. It tells you how you should format your code so that it's easier to read.
Your rewritten and tested code:
from string import punctuation, maketrans
user_sentence = raw_input('Enter a sentence: ')
trans = maketrans("", "")
user_sentence = user_sentence.lower().translate(trans, punctuation).split()
user_word = raw_input('Enter a word from the sentence: ')
user_word = user_word.lower()
if user_word in user_sentence:
print ('Your chosen word appears in the sentence.')