Python While loops with tuples - python

I am writing a function which should count the numbers in an inputted phrase. That phrase gets stored as a tuple and the while loop should count the number of vowels. So far I have gotten this.
def whilephrase():
vowels=['A','a','E','e','I','i','O','o','U','u']
print('Please give me a phrase')
inputphrase=input()
inputphrase=tuple(inputphrase)
i=0
while True:
if vowels in inputphrase:
i=i+1
else:
print(i)
But this just prints out an endless loop of zeros.

You need to iterate over your inputphrase:
for character in inputphrase:
if character in vowels:
i = i + 1
print(i)
But there is, of course, an easier way:
def count_vowels(string):
return sum(1 for c in string if c.lower() in "aeiou")
edit: Using a while loop (although I'm not sure why you want specifically that):
index = 0
i = 0
while index < len(inputphrase):
if inputphrase[index] in vowels:
i += 1
index += 1
print(i)

print len([i for i in inputphrase if i in vowels])

you can also use collections
from collections import Counter
sum([Counter(inputphrase)[i] for i in vowels])

Related

Python: list index out of range when trying to compare two strings at index?

I have this function to check if a string contains three or more lowercase letters.
def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
i = 0
flag = 0
while i <= len(word):
j = 0
while j <= len(lowCharList):
if lowCharList[j] == word[i]:
flag += 1
j = 0
else:
j += 1
i += 1
if flag >= 3:
return True
In simple terms, I pass in a string (word) and create a list of acceptable characters (lowCharList).
Then, I set up a nested while loop that checks word[i] at every index of lowCharList, until it finds a match.
Then it resets lowCharList counter and adds 1 to flag, and moves on to word[i+1].
If it doesn't find a match by the time it reaches z, then it moves onto word[i+1] anyways.
For some reason, why I try my sample input in my main function.
def main():
word = 'corRe!33'
print(lowerCaseValid(word))
I get this error:
in lowerCaseValid
if lowCharList[j] == word[i]:
IndexError: list index out of range
Why is it throwing this error? Thank you.
using python's in operator is easier...
def lowerCaseValid(word):
cnt = 0
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
chars = lowCharList.pop ()
for ch in word:
if ch in chars:
cnt += 1
return cnt >= 3
or with using sets just 2 lines of code
def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
return len(set(lowCharList.pop()) & set(word)) >=3
or one liner with map and lambda
def lowerCaseValid(word):
return len(list(map(lambda x: x.islower, list(word)))) >=3
Another alternative approach using a list comprehension and string.ascii_lowercase instead of redefining the lowercase letters:
from string import ascii_lowercase
def lowerCaseValid(word):
return sum[x in ascii_lowercase for x in word] >= 3
How this works is that the list comprehension goes through each letter in word. The x in ascii_lowercase will return a boolean value of either True (1) or False (0), then sum up the Trues
Change
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
to
lowCharList = list('abcdefghijklmnopqrstuvwxyz')
I believe this should help, since you have a list containing only 1 item, whereas this way, you create a list with 24 items (all different letters).
As heemayl pointed out in the comments, lowCharList is 1 element long! Now you have 2 options: make lowCharList an actual list (lowCharList = list ("abcd...")), or keep lowCharList a string, which will work just fine (remove the brackets in the definition.
Might I suggest another method: checking if str.islower count adds up to >=3. So:
lower_count = 0
for letter in word:
if letter.islower(): lower_count += 1
if lower_count >= 3: return True
Also, as suggested in the comments:
return len ([letter for letter in word if letter.islower()]) >= 3
would work (better than my answer, which is just the expanded form of it)

How to count number of words inside a string using a for loop in python 3

I am trying to write a for loop that finds a specific word inside a string. I know that there is a one liner to do this in python, but I am practicing the for loops and I want to see how using a for I can identify specific words as it identifies especific letters (like vowels). I've been reading some questions, and I think the code should go like this:
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
answer = 0
for i in range(len(s)):
if any(s[i:].startswith(b) for b in s):
answer += 1
print(answer)
but it is not printing anything. I did something similar when I was looking for vowels in the same string, but now I know I am supouse to "arrange" the characters in the word "banana" and then comparate it to the string, that is the porpuse of this part:
if any(s[i:].startswith(b) for b in s):
if you could help me I would really apreciate it.
Thank you.
Your code doesn't print because you don't call the function(you only define it), you should call the function by adding a command at the end:
count_words(s,b)
Your function actually count the number of character in string s:
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
answer = 0
# Loop over each character in s
for i in range(len(s)):
# create a list contain at least current character => any will always return True
if any(s[i:].startswith(b) for b in s):
answer += 1
print(answer)
Right codes:
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
answer = 0
for i in range(len(s)):
if s[i:].startswith(b):
answer += 1
print(answer)
count_words(s,b)
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
answer = 0
counter = 0
if b in s:
for i in range(len(s)):
if s[i]!=b[counter]:
counter=0
else:
counter+=1
if counter == len(b):
answer+=1
counter = 0
print(answer)
count_words(s, b)
Above algorithm first check whether banana exists in s at least once. Then, it will loop to find the count.
If your goal is to use a for loop, you could find the length of the word you're looking for, then check sections of the larger string that are the same length and see if they match. You don't need to use any unless you are intentionally wanting to. Something like this:
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
word_length = len(b)
answer = 0
for i in range(len(s) - len(b) + 1):
if s[i:i+word_length] == b:
answer += 1
return answer
count_words(s,b)
Note I also changed your print to return. It works either way.

How to calculate the number of integers in a python string

I want to calculate the number of integers in the string "abajaao1grg100rgegege".
I tried using isnumeric() but it considers '100' as three different integers and shows the output 4. I want my program to consider 100 as a single integer.
Here is my attempt:
T = int(input())
for x in range(T):
S = input()
m = 0
for k in S:
if (k.isnumeric()):
m += 1
print(m)
I'd use a very basic regex (\d+) then count the number of matches:
import re
string = 'abajaao1grg100rgegege'
print(len(re.findall(r'(\d+)', string)))
# 2
Regex is the go-to tool for this sort of problem, as the other answers have noted. However, here is a solution that uses looping constructs and no regex:
result = sum(y.isdigit() and not x.isdigit() for x,y in zip(myString[1:], myString))
In addition, here is an easy to understand, iterative solution, that also doesn't use regex and is much more clear than the other one, but also more verbose:
def getNumbers(string):
result = 0
for i in range(len(string)):
if string[i].isdigit() and (i==0 or not string[i-1].isdigit()):
result += 1
return result
You can use the regex library to solve this issue.
import re
st = "abajaao1grg100rgegege"
res = re.findall(r'\d+', st)
>>> ['1', '100']
You can check how many numbers you have on that list that the findall returned.
print (len(res))
>>> 2
In order to read more on python regex and the patterns, enter here
Not very Pythonic but for beginners more understandable:
Loop over characters in string and in every iteration remember in the was_digit (logical variable) if the current character is digit - for the next iteration.
Increase the counter only if the previous character was not a digit:
string = 'abajaao1grg100rgegege'
counter = 0 # Reset the counter
was_digit = False # Was previous character a digit?
for ch in string:
if ch.isdigit():
if not was_digit: # previous character was not a digit ...
counter += 1 # ... so it is start of the new number - count it!
was_digit = True # for the next iteration
else:
was_digit = False # for the next iteration
print(counter) # Will print 2
random="1qq11q1qq121a21ws1ssq1";
counter=0
i=0
length=len(random)
while(i<length):
if (random[i].isnumeric()):
z=i+1
counter+=1
while(z<length):
if (random[z].isnumeric()):
z=z+1
continue
else:
break
i=z
else:
i+=1
print ("No of integers",counter)

Counting uppercase letters in a list excluding the first capital in a word

So my function must take a list of strings and return the total number of capital letters that appear in positions other than the beginning of a word. Also to break this problem into a sub problem, it needs a second function that takes a single word and returns the number of capital letters that appear in positions other than the beginning of that word. So far I have a function that works, but I have been told it needs to be done better and I am not quite sure how to do that.
def count_strange_caps(words):
if words[0].isupper():
count = abs(1 -sum(1 for c in words if c.isupper())
elif words[0].islower():
count = abs(sum(1 for c in words if c.isupper()))
return count
def total_strange_caps(words):
total_count = 0
for word in words:
if word[0].isupper():
total_count -= 1
for letter in word:
if letter.isupper():
total_count += 1
return total_count
My teacher told me to combine the two list comprehensions in count_strange_caps as they are basically the same code and use the code from count_strange_caps in the inner for loop for the second function.
print(total_strange_caps(["Five","FiVe","fIVE"]))
print(total_strange_caps(["fIVE"]))
print(count_strange_caps("fIVE"))
These are the types of tests it needs to pass and if anyone could help me with a solution using more rudimentary concepts it would be much appreciated. I can not use numpy if that makes a difference.
You may use str.isupper() and sum() to achieve this. Using these, the function definition of count_strange_caps() should be like:
def count_strange_caps(word):
return sum(my_char.isupper() for my_char in word[1:]) # word[1:] to skip the first character
Sample run:
>>> count_strange_caps('HeLlo')
1
>>> count_strange_caps('HeLLo')
2
>>> count_strange_caps('heLLo')
2
Also, your total_strange_caps() can be simplified using sum() as:
def total_strange_caps(words):
return sum(count_strange_caps(word) for word in words)
Sampl run:
>>> total_strange_caps(['HeLlo', 'HeLLo', 'heLLo'])
5
You can use string comprehension as follows:
def total_strange_caps(words):
total_count = 0
for letter in words[1:]:
if letter.isupper():
total_count += 1
return total_count
print total_strange_caps("AbCdE")
Output:
2

Testing string against a set of vowels - Python

This is a module in my program:
def runVowels():
# explains what this program does
print "This program will count how many vowels and consonants are"
print "in a string."
# get the string to be analyzed from user
stringToCount = input("Please enter a string: ")
# convert string to all lowercase letters
stringToCount.lower()
# sets the index count to it's first number
index = 0
# a set of lowercase vowels each element will be tested against
vowelSet = set(['a','e','i','o','u'])
# sets the vowel count to 0
vowels = 0
# sets the consonant count to 0
consonants = 0
# sets the loop to run as many times as there are characters
# in the string
while index < len(stringToCount):
# if an element in the string is in the vowels
if stringToCount[index] in vowels:
# then add 1 to the vowel count
vowels += 1
index += 1
# otherwise, add 1 to the consonant count
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
else:
print "Your entry should only include letters."
getSelection()
# prints results
print "In your string, there are:"
print " " + str(vowels) + " vowels"
print " " + str(consonants) + " consonants"
# runs the main menu again
getSelection()
However, when I test this program, I get this error:
line 28, in runVowels
stringToCount = input("Please enter a string: ")
File "<string>", line 1
PupEman dABest
^
SyntaxError: unexpected EOF while parsing
I tried adding a + 1 to the "while index < len(stringToCount)" but that didn't help either. I'm pretty new to python and I don't really understand what's wrong with my code. Any help would be appreciated.
I researched this error, all I found out was that EOF stands for end of file. This didn't help at all with resolving my problem. Also, I understand that sometimes the error isn't necessarily where python says the error is, so I double-checked my code and nothing seemed wrong in my eyes. Am I doing this the round-about way by creating a set to test the string elements against? Is there a simpler way to test if string elements are in a set?
Question resolved. Thank you to all!
Looks like you're using Python 2. Use raw_input(...) instead of input(...). The input() function will evaluate what you have typed as a Python expression, which is the reason you've got a SyntaxError.
As suggested use raw_input. Also you don't need to do this:
while index < len(stringToCount):
# if an element in the string is in the vowels
if stringToCount[index] in vowels:
# then add 1 to the vowel count
vowels += 1
index += 1
# otherwise, add 1 to the consonant count
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
else:
print "Your entry should only include letters."
getSelection()
Strings in Python are iterable, so you can just do something like this:
for character in stringToCount:
if character in vowelSet : # Careful with variable names, one is a list and one an integer, same for consonants.
vowels += 1
elif character in consonantsSet: # Need this, if something is not in vowels it could be a number.
consonants += 1
else:
print "Your entry should only include letters."
This should do just fine. Using a while is not necessary here, and very non-Pythonic imho. Use the advantage of using a nice language like Python when you can to make your life easier ;)
You can count the vowels like so:
>>> st='Testing string against a set of vowels - Python'
>>> sum(1 for c in st if c.lower() in 'aeiou')
12
You can do something similar for consonants:
>>> sum(1 for c in st if c.lower() in 'bcdfghjklmnpqrstvwxyz')
26
Also,
if stringToCount[index] in vowels:
should read
if stringToCount[index] in vowelSet:
Here's another way you could solve the same thing:
def count_vowels_consonants(s):
return (sum(1 for c in s if c.lower() in "aeiou"),
sum(1 for c in s if c.lower() in "bcdfghjklmnpqrstvwxyz"))
To wit:
>>> count_vowels_consonants("aeiou aeiou yyy")
(10, 3)
>>> count_vowels_consonants("hello there")
(4, 6)
Python truly is grand.
The errors in your file run as follows (plus some suggestions):
stringToCount = input("Please enter a string: ")
This should be raw_input if you want what the user typed in as a string.
stringToCount.lower()
The .lower() method returns a new string with its letters lowered. It doesn't modify the original:
>>> a = "HELLO"
>>> a.lower()
"hello"
>>> a
"HELLO"
vowelSet = set(['a','e','i','o','u'])
Here you could just as easily do:
vowelSet = set("aeiou")
Note you also don't strictly need a set but it is indeed more efficient in general.
# sets the vowel count to 0
vowels = 0
# sets the consonant count to 0
consonants = 0
Please, you don't need comments for such simple statements.
index = 0
while index < len(stringToCount):
You usually don't need to use a while loop like this in python. Note that all you use index for is to get the corresponding character in stringToCount. Should instead be:
for c in stringToCount:
Now instead of:
if stringToCount[index] in vowels:
vowels += 1
index += 1
You just do:
if c in vowels:
vowels += 1
elif stringToCount[index] != vowels:
consonants += 1
index += 1
# any other entry is invalid
Not quite right. You're checking that a character doesn't equal a set. Maybe you meant:
elif c not in vowels:
consonants += 1
But then there'd be no else case... Got to fix your logic here.
print "In your string, there are:"
print " " + str(vowels) + " vowels"
print " " + str(consonants) + " consonants"
The above is more pythonically written as:
print "In your string, there are: %s vowels %s consonants" % (
vowels, consonants)
# runs the main menu again
getSelection()
Not sure why you're calling that there - why not call getSelection() from whatever calls runVowel()?
Hope that helped! Enjoy learning this great language.
Bah, all that code is so slow ;). Clearly the fastest solution is:
slen = len(StringToCount)
vowels = slen - len(StringToCount.translate(None, 'aeiou'))
consonants = slen - vowels
...note that I don't claim it's the clearest... just the fastest :)

Categories