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
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()
Ive created some code that for now just adds strings to a list till the user decides to quit, and then it returns the first value of that list.
wordList = []
while 1:
user_input = input("Enter a word (or type QUIT to quit): ")
if user_input=="QUIT":
break
wordList.append(user_input)
for i in wordList:
newList = wordList[0]
print ("list of characters: " + str(newList))
print()
however, what I require is to be able to print the nth character of each word. So for example if n was 5 the following you return
Enter a word (or type Q to quit): A
Enter a word (or type Q to quit): ABCDE
Enter a word (or type Q to quit): wollongong
Enter a word (or type Q to quit): 123456
Enter a word (or type Q to quit): frog
Enter a word (or type Q to quit): Q
List of characters:
['E', 'o', '5']
wordList = []
while 1:
user_input = input("Enter a word (or type QUIT to quit): ")
if user_input=="QUIT":
break
if len(user_input) > 4:
wordList.append(user_input[4])
print ("list of characters: " + str(wordList))
print()
Enter a word (or type QUIT to quit): A
Enter a word (or type QUIT to quit): ABCDE
Enter a word (or type QUIT to quit): wollonglong
Enter a word (or type QUIT to quit): 123456
Enter a word (or type QUIT to quit): frog
Enter a word (or type QUIT to quit): QUIT
list of characters: ['E', 'o', '5']
You're nearly there but it looks as if you're getting confused a little with the [] notations. If you have a variable followed by squared brackets it selects the position. So for example lets look at your list called wordList.
print(wordList[0])
the output would be "A".
print(wordList[1])
the outbut would be "ABCDE"
The same applies to strings (words/numbers here for you). So if you're just wanting to print out the 5th letter of a string you can use myString[4] (little confusing but [4] is the 5th letter as 0 counts). Using this logic if we look at your loop.
for i in wordList:
newList = wordList[0]
this doesn't make too much sense are you are just setting a variable called newList equal to the 1st input of wordList over and over again. If I were to solve this problem I would use a loop to first find out if words are larger than 5 characters, if they are add them to a new list. And then use another loop to print out the nth character of every input of the new list we just created. Have a little go if this makes anymore sense and let me know if you need anymore help.
You need to modify your code to save the nth element of the list and not the first:
wordList = []
n = 5
while 1:
user_input = input("Enter a word (or type QUIT to quit): ")
if user_input=="QUIT":
break
wordList.append(user_input)
for i in wordList:
if len(newList) > n: # check if your list has more than n elements
newList = wordList[n] # store the nth element
print ("list of characters: " + str(newList))
print()
result = []
for word in wordList:
if len(word) >= 5:
result.append(word[4])
And result[] will be having the 5th character(here you specified 5) for each of the word in wordList.
So generally if we need nth character
result = []
for word in wordList:
if len(word) >= n:
result.append(word[n - 1])
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
...
I wrote this program, but it doesn't work because, I cannot figure out what it is doing when i input two words seperated by a space
sinput = input("Enter a sentence") #Collects a string from the user
x = len(sinput) #Calculates how many characters there are in the string
for n in range(x):
n = 0 #Sets n to 0
lsinput = sinput.split(" ") #Splits sinput into seperate words
lsinput = lsinput[n] #Targets the nth word and isolates it into the variable lsinput
print(lsinput[1]) #Prints the 1st letter of lsinput
n += 1 #Adds 1 to n so the loop can move on to the next word
i recommend starting with a beginner's book on python. not sure what. but definitely do some reading.
to answer your question to help get you going though, you can just do this:
[w[0] for w in sinput.split() if w]
The problem was that you:
set n back to 0 at every loop
you looped over the wrong amount of iterations
you used 1 to retrieve the first letter rather than 0 (indexes start at 0)
Adjusting this for your code:
sinput = input("Enter a string to convert to phonetic alphabet") #Collects a string from the user
lsinput = sinput.split(" ") #Splits sinput into seperate words
x = len(lsinput) #Calculates how many characters there are in the string
n = 0 #Sets n to 0
for n in range(x):
print(lsinput[n][0]) #Prints the 1st letter of the nth word in 5lsinput
n += 1 #Adds 1 to n so the loop can move on to the next word
I also moved lsinput forward so that you don't recalculate this list with every iteration.
I am not sure i really understood the question, but if you want to get all the first letters of each word in the input this code will do it
map(lambda x: x[0], sinput.split(" "))
Hi all I know there may have been a few similar questions asked already but I would appreciate it if you could give me a more specific solution for what I have attempted.
Basically the program should return the shortest word in the list. The shortest word cannot be an empty string. <-- I'm also not sure how to do this part.
Thanks for the help! : )
Main Program:
n = int((input("Enter amount of words: "))
sw = st.word(n)
print("The shortest word is: {0:.s}" .format(sw))
Function:
def word(n):
l1 = []
for i in range(n):
words = str(input("Enter word: "))
l1.append(words)
s = l1
nxt = l1
for i in range(n+1):
if s[i] < nxt[i+1]:
smallest = s[i]
if nxt[i+1] < s[i]:
smallest = nxt[i+1]
return smallest
You could just use build in min function:
l = ["ab", "abc", "", "fff", "gdfgfdg","a", "3455"]
print(min((word for word in l if word), key=len))
# results in: a
Some explanation:
(word for word in l if word) is generator expression,
if word condition assures that empty strings are not used,
key=len
uses length of each word to look for a minium
You should always prefer to use built-in functions rather than writing your own (maybe except the cases when you are learning). #Marcin describes the work of min function very well, so, I want to present you a filter function as a replacement for generator expressions.
Let's see the way how min and filter may work together:
In [1]: l = ["ab", "abc", "", "fff", "gdfgfdg","a", "3455"]
In [2]: min(filter(None, l), key=len)
Out[2]: 'a'
It may be less intuitive, comparing with #Marcin solution, but I prefer to use high order functions, instead of generators. Reading the text, where one word has 40% frequency (word for word in l if word - 3 / 7) - no, thanks :).
Just a quote from documentation:
In [3]: filter?
Type: type
String form: <class 'filter'>
Namespace: Python builtin
Docstring:
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true
If you want first minimum word.
n = raw_input('Enter words breaking with spaces:')
wordList = n.split()
print min([(word, len(word)) for word in wordList], key=lambda x:x[1])
If you want all the minimum words.
n = raw_input('Enter words breaking with spaces:')
wordList = n.split()
minimunWordLength = min([len(word) for word in wordList])
minimunWords = filter(lambda x:len(x) == minimunWordLength,wordList)
print minimunWords
Algo:
Get User Input for numbers words by raw_input(). Handle exception handling when user enters wrong input i.e. non integer value.
Check enter number is grater then 0 or not. If yes the go to next steps. otherwise print You enter value less then 1.
Call getSmallWord function, pass words counter as argument.
Use for loop and range function to accept word from the user and add to set variable because words may be duplicates from the user, set will not add duplicate words.
Assign first element from the set as smallest and remove this word from the set.
Iterate every element from the set and check if current element i.e. word length is smaller then smallest word then assign this word as smallest.
Return smallest word.
print result.
Demo:
def getSmallWord(n):
#- Use set because set will add one one word when user enter duplicate words.
words = set()
for i in range(n):
word = raw_input("Enter word: ")
words.add(word)
#- Assign First word as smallest.
smallest_word = words.pop()
#- Iterate words from the 1 index. because we assign 0th element as Smallest.
for word in words:
#- Check Lenght of current elemnt from the User Input with the Smallest Word.
if len(word)<len(smallest_word):
smallest_word = word
return smallest_word
if __name__=="__main__":
try:
n = int(raw_input("Enter amount of words: "))
except ValueError:
n = 5
print "Enter Wrong number input. Number of Words are %d"%n
if n>0:
sw = getSmallWord(n)
print "The shortest word is: %s" %sw
else:
print "You enter value less then 1."
Output:
vivek#vivek:~/Desktop/stackoverflow/anna$ python 8.py
Enter amount of words: 5
Enter word: qwert
Enter word: asdf
Enter word: as
Enter word: asdf
Enter word: qwer
The shortest word is: as
Note:
Use raw_input() for Python 2.x
Use input() for Python 3.x