Function to count upper/lower case letters - python-2.7

Could you please help me with writing a function to count alphabetic characters. My current output for this code is like this:
It contains 5 alphabetic characters of which 4 ( 80.0 %) are 'h'
My output for this code should be like this:
It contains 5 alphabetic characters of which 5 ( 100.0 %) are 'h'. I would like to treat both upper/lowercase letters equally
def count(p):
lows = "abcdefghijklmnopqrstuvwxyz"
ups = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numberOfh = 0
totalChars = 0
for achar in p:
if achar in lows or achar in ups:
totalChars = totalChars + 1
if achar == 'h':
numberOfh = numberOfh + 1
percent_with_h = (numberOfh / totalChars) * 100
print("It contains", totalChars, "alphabetic characters of which", numberOfh, "(", percent_with_h, "%)", "are 'h'.")
p = "Hhhhh"
count(p)

print p.lower().count("h")
I think should do what you want

Just change if statement to
if achar == 'h' or achar == 'H':
If you want to count all 'h' and 'H'.

If you want to count the occurrence of any letter in your string, rather than just h you could use something like this, which returns a dictionary containing each letter as the key, and the percentage as the value:
def count_alphas(s):
s = s.lower()
alpha_set = set(s)
alpha_counts = {}
for x in alpha_set:
alpha_counts[x] = s.count(x) / float(len(s)) * 100
return alpha_counts
# an example use:
print(count_alphas('thisissomeexampletext'))

Related

Seperate numbers and Letters & Rearrange the String: Variable Letters Has an Incorrect Value

Write the function Separator that:
Input: inString -- random string scalar mixed with numbers & letters
Tasks:
Seperate Numbers & Letters
Calculate Sum of Numbers
Count Number of Letters (the white spaces counted)
Output:
numbers, string scalar of all numbers in inString with same order.
letters, string scalar of all letters in inString with same order, and white spaces Does Not removed.
sumofNumbers, double precision scalar of sum of all numbers in inString.
numberofLetters, double precision scalar to count all letters in inString, white spaces counted.
Expected Result:
inString: "eng12in13e143e553rin154g 6p547ro548bl645em 8s65ol9v56ing"
numbers: "12131435531546547548645865956"
letters: "engineering problem solving"
sumofNumbers: 131
numberofLetters: 27
Here's My Code:
function [numbers, letters, sumofNumbers, numberofLetters]=Separator(inString)
%Insert your code here
indexNum = regexp(char(inString), '[0-9]')
numbers = []
for i = 1:numel(indexNum)
numbers = [numbers , inString{1}(indexNum(i))]
end
% numbers
numbers = string(numbers)
% sumofNumbers
sumofNumbers = 0
for i = 1:numel(indexNum)
sumofNumbers = sumofNumbers + str2num(numbers{1}(i))
end
words = split(inString)
letters = []
count = 0
for i = 1:numel(words)
indexLett = regexp(char(words(i)), '[a-z]')
count = count + numel(indexLett)
for j = 1:numel(indexLett)
letters = [letters, words{i}(indexLett(j))]
end
letters = strcat(string(letters), " ")
letters = char(letters)
end
% letters
letters = strip(string(letters))
comb = split(letters)
letters = join(comb)
% number of Literal Letters
numofTrueLetters = count
% numberofLetters
numberofLetters = 0
numberofLetters = strlength(letters)
end
The Code Returns Exactly As the Expected:
numbers =
"12131435531546547548645865956"
letters =
"engineering problem solving"
sumofNumbers =
131
numberofLetters =
27
However, the MATLAB Grader gives this Answer: "Variable Letters Has an Incorrect Value" and I was confused.
I would be very appreciated if someone could point out the mistake or the error, thank you!
Alright I got this!
I modified this line, before "[a-z]" and now is "[A-Za-z]" which checks all upper and lower cases for case-insensitivity.
indexLett = regexp(char(words(i)), '[A-Za-z]')
By this way, the indexLett would record all the indexes in the string that has alphabetic letters regardless of case-sensitive,
so for more inputs like
"Apple is good for health"
or
"A42pp3113le31 is 31g11oo456d fo442r h105ea422l44t2h"
could be counted as the capitalized words in the string.

python Find the longest substring without any number and at least one upper case character

I've been stuck trying to figure out how to find the longest substring with no numbers and at least one uppercase. Especially when it comes to at least one upper case. I tried iterating over the string and appending the element to a new list. Then if the element came to a number, I tried to see if any of the elements in a new list had a capital letter. Any help will be appricated. Thank you
Algorithm Overview:
Iterate over the string, if we see a number then add the substring before that number to a dictionary, where the key is the length of the substring and the value is the substring. Return the max-length substring.
The code for this is as follows:
def longestSubstring(s):
max_length = 0
tmp_length = 0
tmp_uppercase_count = 0
tmp_string = ""
strings = {}
nums = '0123456789'
s_length = len(s)
for i in range(s_length):
if s[i] not in nums:
if s[i].upper() == s[i]:
tmp_uppercase_count += 1
tmp_length += 1
tmp_string += s[i]
if tmp_uppercase_count > 0 and i == s_length - 1:
strings[tmp_length] = tmp_string
max_length = max(max_length, tmp_length)
else:
if tmp_uppercase_count > 0:
strings[tmp_length] = tmp_string
max_length = max(max_length, tmp_length)
tmp_length = 0
if i != s_length - 1:
tmp_string = ""
tmp_uppercase_count = 0
if len(strings) == 0 and tmp_uppercase_count > 0:
return tmp_string
elif len(strings) == 0:
return ""
else:
return strings[max_length]
Note that instead of going for shorter code, I looked more for time complexity. This code runs in O(N) time.

Convert results in python to dictionary

help to convert a python code results, where its finding the number of time the vowel appears in a string to dictionary?
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in s:
if char in vowels:
count += 1
print ('Number of vowels: ' + str(count))
The result should be:
for apple: {'a' : 1, 'e' : 1}
A simple change like this would do: instead of incrementing count += 1, increment directly on a dictionary:
count = 0
s = "apple"
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
vowels_dict = {}
for char in s:
if char in vowels:
if char in vowels_dict:
vowels_dict[char] +=1
else:
vowels_dict[char] = 1
print (vowels_dict)
First, let's make vowels into a dictionary . We will need a second one to hold on to the matches we make in the first loop:
s = "apples"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
We will need to modify your for loop slightly to increment the value of the corresponding key (the vowels):
for char in s:
if char in vowels:
vowels[char] += 1
The for loop above checks if char is a vowel (or put simply, is one of the keys found in vowels). If it is, we increment the corresponding key's value by 1. For example, if char was "a", the if statement would return True and the key ("a")'s value (the integer after the colon) will increase by one. Now all we need is to put all the keys whose value is over 0 into the matches dictionary:
for vowel in vowels:
if vowels[vowel] < 1: # The vowel didn't appear in the word
continue
else:
matches[str(vowel)] = vowels[vowel]
The last line creates a new key for the matches dictionary (the matches[str(vowel)] part) then assigns the value of the new key equal to the value of the respective key in the vowels dictionary (the = vowels[vowel] part). Now all we need to do is to print out the matches dictionary:
print matches
Full code:
count = 0
s = "apple"
vowels = dict.fromkeys('aeiou', 0)
matches = {}
for char in s:
if char in vowels:
vowels[char] += 1
for vowel in vowels:
if vowels[vowel] < 1:
continue
else:
matches[str(vowel)] = vowels[vowel]
print matches

How to double a char in a string?

I am trying to write a function that takes two arguments, a string and a letter. The function should then double the number of letter in the string. For example:
double_letters("Happy", "p")
Happppy
what i have done so far;
def double_letter(strng, letter):
new_word = ""
for char in strng:
if char == letter:
pos = strng.index(char)
new_word = letter+strng[pos:]
But this is giving me the output: pppy
how can i change the function to get the output: Happppy?
Use string.replace
string = 'happy'
letter = 'p'
string = string.replace(letter, letter + letter)
print string
You could use join and iterate through the characters in your string:
def double_letters(word, letter):
return "".join(2*i if i == letter else i for i in word)

Manipulating strings python 2.7

I am trying to code a program that will insert specific numbers before parts of an input, for example given the input "171819-202122-232425" I would like it to split up the number into pieces and use the dash as a delimiter. I have split up the number using list(str(input)) but have no idea how to insert the appropriate numbers. It has to work for any number Thanks for the help.
Output =
(number)17
(number)18
(number)19
(number+1)20
(number+1)21
(number+1)22
(number+2)23
(number+2)24
(number+2)25
You could use split and regexps to dig out lists of your numbers:
Code
import re
mynum = "171819-202122-232425"
start_number = 5
groups = mynum.split('-') # list of numbers separated by "-"
number_of_groups = xrange(start_number , start_number + len(groups))
for (i, number_group) in zip(number_of_groups, groups):
numbers = re.findall("\d{2}", number_group) # return list of two-digit numbers
for x in numbers:
print "(%s)%s" % (i, x)
Result
(5)17
(5)18
(5)19
(6)20
(6)21
(6)22
(7)23
(7)24
(7)25
Try this:
Code:
mInput = "171819-202122-232425"
number = 9 # Just an example
result = ""
i = 0
for n in mInput:
if n == '-': # To handle dash case
number += 1
continue
i += 1
if i % 2 == 1: # Each two digits
result += "\n(" + str(number) + ")"
result += n # Add current digit
print result
Output:
(9)17
(9)18
(9)19
(10)20
(10)21
(10)22
(11)23
(11)24
(11)25