I am creating a program that counts the occurrences of each letter in the alphabet that are in the string the user inputs. The user is prompted to keep entering strings until they enter <end> which stops the input and analyzes the inputs.
The analyzing works just fine. The problem occurs when, for example, I enter the first input "thanks", and then the second input, "please". The program will only analyze "please" and not "thanks". I can't figure out why.
programrun = True
while programrun:
stringinput = input ("Enter a sentence or word <END> to finish: ").lower()
if stringinput != "<end>":
stringinput1 = stringinput
letters =['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']
#print (programrun)
if stringinput == "<end>":
programrun = False
#stringinput2 = stringinput1
print (stringinput1)
for i in range(0,26):
#frequency = (int(stringinput.count(letters[i]) / 26) * 100)
length = len(stringinput1)
print(letters[i],": ",stringinput1.count(letters[i]), " Freqency: ", (float(stringinput1.count(letters[i]) / length) * 100))
The problem is the indentation, the for loop was not inside the while loop, so after inputing one word, the code stops, I've add other improvements
you can just use a string with the letters instead of a list, and define it before the loop
iterate directly over each letter, not over ints then access by index
stop the code it the input is "<end>" don't do other string manipulation
letters = 'abcdefghijklmnopqrstuvwxyz'
while True:
stringinput = input("Enter a sentence or word <END> to finish: ").lower()
if stringinput == "<end>":
break
for letter in letters:
length = len(stringinput)
count = stringinput.count(letter)
print(letter, ": ", count, " Freqency: ", (count / length) * 100)
I think because, you need to concatenate all entries in stringinput1:
stringinput1=""
while programrun:
stringinput = input ("Enter a sentence or word <END> to finish: ").lower()
if stringinput != "<end>":
stringinput1 = stringinput1+stringinput
...
Related
I'm trying to find find the longest string entered then print it as the output value. The program stops running when an 'a' has been entered then returns the longest string entered not just the numbers of characters in the string. Can the length function do this?
def longest_str(words):
words = len(words)
return words
true = 1
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
if words.startswith('a'): #comparing if starts with a or A
print(f"The longest string was: {longest_str(words)}") # printing output
break #stop once reached a
else:
continue # continue to loop through, no a was found.
I understand what you are trying to do but you have several mistakes
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
This will read only one word at the time.
So, your if will be executed only if you enter a word starting with 'a'.
This will solve your problem
def longest():
maxLength = 0
longestWord = ''
while(True):
word = str(input("Enter a string: "))
word = word.lower()
if word == 'a':
print(f"The longest string was: {longestWord}")
break
if len(word) > maxLength:
maxLength = len(word)
longestWord = word
Take a look at the differences
We check if the word entered is 'a', then print the longest string and stop.
If not, we check if the new word is longer than what we previously had (initialy nothing).If the new word is longer, we retain it to be able to print it.
Just call this in the main function.
If you want the string itself you could just do it like this:
longest_string = ''
while True:
word = input("Enter a string: ").lower()
if word == 'a': break
if len(word) > len(longest_string):
longest_string = word
print("The longest string was: " + longest_string)
Keep in mind, this will make ALL words lowercase, if you dont want that you have to remove the .lower()
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.
I need a simple Python Hangman program without using Lists - It is just one word
HAPPY - this program works - BUT...
This is what I did, with Lists - but teacher said Lists are not allowed
We do not have to draw hangman - we just prompt for the letters - print the "-" for each letter to show length of word.
def main():
secretword = "HAPPY"
displayword=[]
displayword.extend(secretword)
for I in range (len(displayword)):
displayword[I]="_"
print ('current word
')
print (' '.join(displayword))
count = 0
while count < len(secretword):
guess = input('Please guess a etter: ')
for I in range(len(secretword)):
if secretword[I] == guess:
displayword[I] = guess
countr - count + 1
print (' '.join(displayword))
print (congratulations you guess the word')
main()
If you don't like the code - that's fine. This is how our teacher is requiring us to do this. I can see it is not like others do it. I only left out the comments - that are also required on every line of code
One solution to your problem would be to use two strings, secretword, which is the word you're looking for and displayword which is what the user sees so far, the combination of letters and -. Every time you enter a letter, the program checks if the secretword contains that letter and if it does, it updates the character of the specific index in displayword:
def main():
secretword = "HAPPY"
length = len(secretword)
displayword = '-' * length
count = 0
while count < length:
guess = input("Please guess a letter: ")
for i in range(length):
if secretword[i] == guess:
displayword[i] = guess
count += 1
print(displayword)
print("Congratulations, you guessed the word.")
main()
This is my caesar cipher so far- it works with spaces but it won't work with capitals. Can you please help me put in an IF statement to get it to work?
I've tried:
elif letter==letter.upper():
finalphrase=alphabet[(alphabet.index(letter)+offset)%26].upper()
but it still doesn't work...
#Caesar Cipher - Encrypts/Decrypts the user's input
#Asking the user if they want to encrypt or decrypt a word/phrase
EorD = input("Please input either 'e' (for encrypt) or 'd' (for decrypt): ")
#IF Statement to decide whether the offset gets saved as a positive or a negative integer
if EorD.lower() == 'e':
offset = int(input("Please input your chosen offset: "))
elif EorD.lower() == 'd':
offset = -int(input("Please input your chosen offset: "))
else:
print("Error")
#Asking the user for their phrase
phrase = input("Please input a word/phrase: ")
#alphabet stored in 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"]
#A FOR loop - to loop through the individual letters in the phrase
for letter in phrase:
if letter in alphabet:
finalPhrase = alphabet[(alphabet.index(letter)+offset)%26]
else:
finalPhrase = letter
print(finalPhrase, end="")
Replace
alphabet.index(letter)
by
alphabet.index(letter.lower())
RĂ©mi was able to show you what you had wrong in your index search. I'd also like to add that the if statement in the for loop could be:
if letter.lower() in alphabet:
This will return the cipher as a lowercase, but from here I think you should be able to figure out the rest if you want to return an uppercase solution.
I did it!!!
for i in word:
if i in alphabet:
newword = alphabet[(alphabet.index(i)+offset)%26]
elif i==i.upper():
newword = alphabet[(alphabet.index(i.lower())+offset)%26].upper()
else:
newword = i
print(newword, end="")
I'm a noob so please excuse me.
There are three lists
A list of letters L = ['A','B','C','D','E']
A list of numbers N = ['1','2','3','4','5']
A list of number strings List = ['124','351']
These are the steps I wish to achieve
Request a letter from the user e.g. A
Find the letter in the letter list L and record its numerical position e.g. [0]
Use the same numeric position in the list of numbers N and record the
number that's there e.g. 1
Replace the instances of the number found in the non-letter strings List e.g. ['124','351'] becomes ['A24','35A']
Ask the user for the next letter until all the number strings become letters.
What I have achieved so far is the first 4 steps. After step 4 I thought to check if the number strings still contained numbers and if so go to step 5. I can't seem to work out how to get the code to check if the number strings contain any more number. NOTE: The number list is not limited to numbers. It could contain math symbols e.g. + or -
L = ['A','B','C','D','E']
N = ['1','2','3','4','5']
list = ['124','351']
print ("Enter a letter")
# Is there a number in List
# If yes then do the following else print List
# Ask for a letter from the user
letter = input ("Enter letter: ")
# Confirm whether the letter is correct or not
if letter in L:
# Find the position of the letter in the list
position = (L.index(letter));
# Make a variable called number with value at the same position in the N list
number = N[position];
# Replace the numbers in the List with the letter entered
list = [item.replace(number, letter) for item in list];
# Print the list with the numbers replaced
print (list, "\n");
print ("Please guess again. \n");
letter = input ("Enter a letter now: ")
# repeat until the List only contains letters
else:
print ("That is not correct");
print ("Please guess again. \n");
letter = input ("Enter a letter now: ")
I hope that is OK. If you need anything further please let me know
L = ['A','B','C','D','E']
N = ['1','2','3','4','5']
n_strings = ['124','351'] # Don't use list as a variable name
while not all( x.isalpha() for x in n_strings): # keep going until all are alpha chars
print ("Enter a letter")
# Is there a number in List
# If yes then do the following else print List
# Ask for a letter from the user
letter = input("Enter letter: ")
# Confirm whether the letter is correct or not
if letter in L:
# Find the position of the letter in the list
position = (L.index(letter));
# Make a variable called number with value at the same position in the N list
number = N[position];
# Replace the numbers in the List with the letter entered
n_strings = [item.replace(number, letter) for item in n_strings];
# Print the list with the numbers replaced
print (n_strings, "\n");
print ("Please guess again. \n");
letter = input("Enter a letter now: ")
# repeat until the List only contains letters
else:
print ("That is not correct");
print ("Please guess again. \n");
letter = input("Enter a letter now: ")
You could change the logic and shorten the code.
while True:
if all(x.isalpha() for x in n_strings ):
print("All guessed correct {}".format(n_strings)) # if all are alpha print final n_string and break out of loop
break
print n_strings
letter = input("Please enter a letter: ")
if letter in L:
# Find the position of the letter in the list
position = (L.index(letter));
number = N[position];
n_strings = [item.replace(number, letter) for item in n_strings];
print (n_strings, "\n");
# repeat until the List only contains letters
else:
print ("That is not correct");
print ("Please guess again. \n");
I can't seem to work out how to get the code to check if the number
strings contain any more number
You could define a function that loops over the list to see if any of the entries have digits using using isdigit() like so
def has_number(lst):
for s in lst:
if any(x.isdigit() for x in s):
return True
return False
This will return True if any of the entries in your number string list contains a number
Saw your edit
My goal is for it to contain letters only
To do that you could just check like this
if all(x.isalpha() for x in lst):
# lst contains only entries that consists of letters
This uses isalpha()
str.isalpha()
Return true if all characters in the string are
alphabetic and there is at least one character, false otherwise.
Demonstration:
>>> all(x.isalpha() for x in ['abc', 'def'])
True
>>> all(x.isalpha() for x in ['ab1', 'def'])
False