Python: 2 Conditions - Read in characters Until x, and Count Vowels - python

Specification: Read in characters until the user enters a full stop '.'. Show the number of lowercase vowels.
So far, I've succeeded in completing the read loop and printing out 'Vowel Count: '. However, vowel count always comes to 0.
I've just started. I'm struggling with placement for 'Show the number of lowercase vowels'
Should I define vowels = ... at the top? Or put it in a loop later? Do I create a new loop? I haven't been able to make it work.
Thanks
c = str(input('Character: '))
count = 0
while c != '.':
count += 1
c = str(input('Character: '))
print("Vowel count =", count)

Here is the solution of your problem. You should add 2 conditions in your code. You check If the character is vowel and if is lowercase:
c = str(input('Character: '))
count = 0
while c != '.':
if c in 'aeyio' and c.islower():
count += 1
c = str(input('Character: '))
print("Vowel count =", count)

In while Loop you can add if condition to check if letter is in lower case using string method islower() and is letter is vowel. if both condition satisfy then increase count by 1.
You don't have to convert input string into str type since input string is always in string type.
Also, outside while loop you can declare variable as empty string.
c =''
count = 0
while c != '.':
c = input('Character: ')
if c.islower() and c in ('a','e','i','o','u'):
count += 1
print("Vowel count =", count)

Lowercase Vowels correspond to a set of numbers in the ascii table, same case applies to the '.'
c = str(input('Character: '))
count = 0
lowerCaseVowel = [97, 101, 105, 111, 117]
for _ in c:
# check for .
if ord(_) == 46:
break
if ord(_) in lowerCaseVowel:
count += 1
print("Vowel count = ", count)

Related

the count function will not work properly

i = input("enter")
count = 0
if i in"abcdefghijklmnopqrstuvwxyz":
count = count+1
if i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
count = count+1
if i in "1234567890":
count = count+1
if i in "#!£%^&*()_+{}:?><":
count = count+1
print(count,I)
when I input say, a or A or 1 or ! just by themselves as a single character count will = to 1. however, when I input more than one such as 'aA', or 'AA' count will = to 0. why is this?
'aA' in "abcdefghijklmnopqrstuvwxyz" is only true if the exact sequence aA appears somewhere in abcdefghijklmnopqrstuvwxyz, not if any of the characters can be found.
You can use the any() function to test each character separately.
if any(c in "abcdefghijklmnopqrstuvwxyz" for c in i):
count += 1

Why is my python code giving wrong answers for only some inputs?

I am new to python and I was trying to write a program that gives the frequency of each letters in a string from a specific point. Now my code is giving correct output for some inputs like if I give the input "hheelloo", I get the correct output, but if the input is "hheelllloooo", the frequency of h,e and l is printed correct, but the frequency of 'o' comes out as 7 if the starting point is index 0. Can somebody tell me what am i doing wrong.
Write a Python program that counts the occurrence of Character in a String (Do
not use built in count function.
Modify the above program so that it starts counting
from Specified Location.
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1 // <----- This line should be outside the if block.
The error was because of indentation.
I have just properly indented the last line.
Thanks, if it works, kindly upvote.
string module can be useful and easy to calculate the frequency of letters, numbers and special characters in a string.
import string
a='aahdhdhhhh2236665111...//// '
for i in string.printable:
z=0
for j in a:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
If you want to calculate the frequency of characters from a particular index value, you just have to modify the above code a little as follows:
import string
a='aahdhdhhhh2236665111...//// '
c = int(input("Enter the location from which the count needs to start : "))
for i in string.printable:
z=0
for j in a[c:]:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
I don't think you need to map the input to list of str as input() always returns a string and string itself is a list of characters. Also make sure you don't use the built-ins as your variable names (As str used in your code). One of the simpler approach can be:
input_word = input("Enter the string : ")
c = int(input("Enter the location from which the count needs to start : "))
# Dict to maintain the count of letters
counts = {}
for i in range(c, len(input_word)):
# Increment 1 to the letter count
counts[input_word[i]] = counts.get(input_word[i], 0)+1
for letter, freq in counts.items():
print (f'{letter} appears {freq} times')
Output:
Enter the string : hheelllloooo
Enter the location from which the count needs to start : 2
e appears 2 times
l appears 4 times
o appears 4 times

How to find vowels in the odd positions of a string?

For my code, I have to make a function that counts the number of vowels in the odd positions of a string.
For example, the following will produce an output of 2.
st = "xxaeixxAU"
res = countVowelsOdd(st)
print (res)
For my code, the only problem I have is figuring out how to tell python to count the vowels in the ODD positions.
This is found in the second part of the "if statement" in my code where I tried to make the index odd by putting st[i] %2 == 1. I get all types of errors trying to fix this.
Any idea how to resolve this?
def countVowelsOdd(st):
vowels = "aeiouAEIOU"
count = 0
for i, ch in enumerate(st):
if i in vowels and st[i] % 2 == 1:
count += 1
return count
if i in vowels ...
i is the index, you want the letter
if ch in vowels ...
and then since you have the index, that is what you find the modulo on
if ch in vowels and i % 2 == 1:
enumerate provides you first argument i as position.
def countVowelsOdd(st):
vowels = "aeiouAEIOU"
count = 0
for i, ch in enumerate(st):
if ch in vowels and i % 2 == 1:
count += 1
return count
I don't know if your assignment/project precludes the use of regex, but if you are open to it, here is one option. We can first do a regex replacement to remove all even-positioned characters from the input. Then, do a second replacement to remove all non-vowel characters. Finally, what remains gives us correct vowel count.
st = "xxaeixxAU"
st = re.sub(r'(.).', '\\1', st)
print(st)
st = re.sub(r'[^aeiou]', '', st, flags=re.IGNORECASE)
print(len(st))
This prints:
xaixU
3
Please, have a look at this
In [1]: a = '01234567'
In [2]: print(*(c for c in a[0::2]))
0 2 4 6
In [3]: print(*(c for c in a[1::2]))
1 3 5 7
In [4]: print(*(c in '12345' for c in a[1::2]))
True True True False
In [5]: print(sum(c in '12345' for c in a[1::2]))
3
does it help with your problem?

Function to count small and Capital letters in a string

I wrote a function which takes a string and gives back the count of small letters and the count of capital letters in that string. The program works for single word but as soon I add two words containing 'space' in between two words, messes things up. spaces counts too.
What is your thoughts?
def myfunc(s):
s = str(s)
upperl = 0
lowerl = 0
for i in s:
if i == i.lower():
lowerl += 1
if i == i.upper():
upperl += 1
if i == ' ':
continue
return upperl,lowerl
x = myfunc('hello G')
print (x)
from the word 'hello G' we expect upper letter and lower letter
count as 1,5 but that space between two words makes it 2,6.
The problem is that ' ' == ' '.upper() and ' ' == ' '.lower() are both true, and you're not checking whether you're currently dealing with an alphanumeric character or something else. Instead, you can check whether you're working with a lowercase letter or an uppercase letter.
Try this:
def calculate_case_count(string: str):
string = str(string)
upper_letter_count = 0
lower_letter_count = 0
for letter in string:
if letter.islower():
lower_letter_count += 1
elif letter.isupper():
upper_letter_count += 1
return upper_letter_count, lower_letter_count
result = calculate_case_count('hello G ')
print(result) # (1, 5)
Using regex will be cleaner solution here
import re
def count_letter_cases(text):
n_lower = len(re.findall("[a-z]", text))
n_upper = len(re.findall("[A-Z]", text))
return n_lower, n_upper
print(count_letter_cases("Hello Goat"))
## Result: (7,2)
from collections import Counter
def count_cases(strng):
counts = Counter(strng)
upper = 0
lower = 0
for char, count in counts.items():
if char.isupper():
upper += count
elif char.islower():
lower += count
return (upper, lower)
Edit: Removed string module. Using internal islower and isupper methods.

Using a for loop to count the number of total letters and the number of a specific letter\

For a school project I have to write a function that counts the number of letters in a string, but also counts the number of a specific letter, however it only seems to increase the total letter count when it is the specified letter. I don't understand why it isn't registering ascii_lowercase as the lower case alphabet in 3.7, unless i have drastically misunderstood something.
def analyze_string(quote, search_letter):
count_letters = 0
count_occurance = 0
phrase = quote.lower()
letter = string.ascii_lowercase
length = len(phrase)
for i in phrase:
if i == letter:
count_letters = count_letters + 1
elif i == search_letter:
count_letters = count_letters + 1
count_occurance = count_occurance + 1
else:
count_letters = count_letters + 0
return count_letters, count_occurance
This line is problematic:
if i == letter:
You have assigned to letter a string containing all lowercase letters via string.ascii_lowercase. But i is just one letter. You can instead use:
if i in letter:
# ...
Checking membership of a string takes O(n) time. You may wish to use set to reduce this to O(1) beforehand via a conversion:
letter = set(string.ascii_lowercase)
You then need to reverse the order of your if statements so that the check for search_letter takes precedence. Otherwise, if search_letter exists in letter, the second condition will never be met.
for i in phrase:
if i == search_letter:
count_letters = count_letters + 1
count_occurance = count_occurance + 1
elif i in letter:
count_letters = count_letters + 1
Note the below lines are redundant, you can safely remove them:
else:
count_letters = count_letters + 0

Categories

Resources