Use Count to count the number of characters in two separate strings - python

I am trying to use count to count the number of characters in two separate strings. I can get it to work for just one but how can I format it to count for two strings? I have tried using 'and' but it is not working. What I want is when the user enters inputs for name1(Anna) and name2(Andy) I want the result to be 3 counting the letter 'a' in both names.
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
lower1 = name1.lower()
lower2 = name2.lower()
a = lower1.count("a") and lower2.count("a")
print(a)

and is boolean operator.
The expression x and y first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is
returned.
You want to use addition
a = lower1.count("a") + lower2.count("a")

You can also first concatenate the two strings and then count:
a = (lower1 + lower2).count("a")

I suppose you want to add the two counts, right? So simply:
a = lower1.count("a") + lower2.count("a")
print(a)
should be enough in your case.

and is a boolean operator, which cant be used when assigning variables with the sum of two other variables. The correct way is:
a = lower1.count("a") + lower2.count("a")

Related

How does comparing two chars (within a string) work in Python

I am starting to learn Python and looked at following website: https://www.w3resource.com/python-exercises/string/
I work on #4 which is "Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself."
str="restart"
char=str[0]
print(char)
strcpy=str
i=1
for i in range(len(strcpy)):
print(strcpy[i], "\n")
if strcpy[i] is char:
strcpy=strcpy.replace(strcpy[i], '$')
print(strcpy)
I would expect "resta$t" but the actual result is: $esta$t
Thank you for your help!
There are two issues, first, you are not starting iteration where you think you are:
i = 1 # great, i is 1
for i in range(5):
print(i)
0
1
2
3
4
i has been overwritten by the value tracking the loop.
Second, the is does not mean value equivalence. That is reserved for the == operator. Simpler types such as int and str can make it seem like is works in this fashion, but other types do not behave this way:
a, b = 5, 5
a is b
True
a, b = "5", "5"
a is b
True
a==b
True
### This doesn't work
a, b = [], []
a is b
False
a == b
True
As #Kevin pointed out in the comments, 99% of the time, is is not the operator you want.
As far as your code goes, str.replace will replace all instances of the argument supplied with the second arg, unless you give it an optional number of instances to replace. To avoid replacing the first character, grab the first char separately, like val = somestring[0], then replace the rest using a slice, no need for iteration:
somestr = 'restart' # don't use str as a variable name
val = somestr[0] # val is 'r'
# somestr[1:] gives 'estart'
x = somestr[1:].replace(val, '$')
print(val+x)
# resta$t
If you still want to iterate, you can do that over the slice as well:
# collect your letters into a list
letters = []
char = somestr[0]
for letter in somestr[1:]: # No need to track an index here
if letter == char: # don't use is, use == for value comparison
letter = '$' # change letter to a different value if it is equal to char
letters.append(letter)
# Then use join to concatenate back to a string
print(char + ''.join(letters))
# resta$t
There are some need of modification on your code.
Modify your code with as given in below.
strcpy="restart"
i=1
for i in range(len(strcpy)):
strcpy=strcpy.replace(strcpy[0], '$')[:]
print(strcpy)
# $esta$t
Also, the best practice to write code in Python is to use Function. You can modify your code as given below or You can use this function.
def charreplace(s):
return s.replace(s[0],'$')[:]
charreplace("restart")
#'$esta$t'
Hope this helpful.

Occurrence of a letter case sensitive

I am trying to find occurrence of letter 'b' and 'B'. the code that I have written works perfectly. Is there a better way that i can do this.
My code:
def count_letter_b(string):
#TODO: Your code goes here
a = int(string.count('B'))
b = int(string.count('b'))
return a + b
print count_letter_b("Bubble Bungle")
You can turn the string to uppercase (or lowercase), then count the occurrences:
string.upper().count('B')
So, overall, your code will look like this:
def count_letter_b(string):
return string.upper().count('B')
Note: no need to cast to int(..) as the result of str.count is already an int
Well if you only want to apply the same computation to a varying amount of letters you may want them to be arguments (count_letter(s, letters)), but anyway, here is a more functional example:
def count_letter_b(string):
return sum(map(string.count, 'Bb'))
This uses the str.count version that is bound to your input string instance.
Note that you're shadowing the name string if you use it as a parameter name.
You could do
# count in upper string, upper character
def countInvariantChars(c,s):
return s.upper().count(c.upper())
# list comprehensions + length
def countInvariantChars2(c,s):
return len([x for x in s if c.upper() == x.upper()])
# sum ones of list comprehension
def countInvariantChars3(c,s):
return sum([1 for x in s if c.upper() == x.upper()])
print(countInvariantChars("b","Bubble Bungle"))
print(countInvariantChars2("b","Bubble Bungle"))
print(countInvariantChars3("b","Bubble Bungle"))
Output (pyfiddle.io):
read-only#bash: 4
4
4
Use this:
def count_letter_b(string):
return string.lower().count('b')
print(count_letter_b(string))

I am getting the output for the program but not in the required way?

Write a Python function that accepts a string as an input.
The function must return the sum of the digits 0-9 that appear in the string, ignoring all other characters.Return 0 if there are no digits in the string.
my code:
user_string = raw_input("enter the string: ")
new_user_string = list(user_string)
addition_list = []
for s in new_user_string:
if ( not s.isdigit()):
combine_string = "".join(new_user_string)
print ( combine_string)
else:
if ( s.isdigit()):
addition_list.append(s)
test = "".join(addition_list)
output = sum(map(int,test))
print ( output )
the output should be:
Enter a string: aa11b33
8
my output:
enter the string: aa11b33
aa11b33
aa11b33
1
2
aa11b33
5
8
This look suspiciously like homework...
getsum = lambda word: sum(int(n) for n in word if n.isdigit())
getsum('aa11b33')
Out[3]: 8
getsum('aa')
Out[4]: 0
An explanation of how this works piece-by-piece:
The function n.isdigit() returns True if n is composed only of one or more digits, false otherwise. (Documentation)
The syntax for n in word will loop over each item in the iterable word. Since word is a string, python considers each character to be an individual item.
The operation sum(int(n) for n in word...) casts each character to an int and takes the sum of all of them, while the suffix if n.isdigit() filters out all non-digit characters. Thus the end result will just take the sum of all the individual digit characters in the string word.
The syntax lambda x: some expression using x constructs an anonymous function which takes some value x as its parameter, and returns the value of the expression after the colon. To give this function a name we can just put it on the right-hand-side of an assignment statement. Then we can call it like a normal function. Usually it's better to use a normal def getsum(x) kind of function definition, however lambda expressions are sometimes useful for if you have a one-off kind of function you just need to use as a parameter to a function. In general in python it's better if you can find a way to avoid them, as they're not considered very readable.
Here is a complete example:
def sumword(word):
return sum( int(n) for n in word if n.isdigit() )
word = raw_input("word please: ")
print(sumword(word))
It should be
user_string = raw_input("enter the string: ")
new_user_string = list(user_string)
addition_list = []
for s in new_user_string:
if ( not s.isdigit()):
combine_string = "".join(new_user_string)
else:
if ( s.isdigit()):
addition_list.append(s)
test = "".join(addition_list)
output = sum(map(int,addition_list))
print output
You were getting the output you were for two reasons.
In the if statement, you were telling it to print the string that was originally inputted when it came across a non-digit. This makes perfect sense as you look at your output - the string is printed when it sees a, the string is printed when it sees the second a, and the string is not printed, not printed (for the ones) and then the string is printed for the last time with the b.
You were printing the output as the for loop incremented through the list, meaning it printed the total each time. Moving the output variable and print statement outside the for loop fixed the problem.
Python cares about indentations:
user_string = raw_input("enter the string: ")
new_user_string = list(user_string)
addition_list = []
for s in new_user_string:
if ( not s.isdigit()):
combine_string = "".join(new_user_string)
#print ( combine_string)
else:
if ( s.isdigit()):
addition_list.append(s)
test = "".join(addition_list)
output = sum(map(int,test))
print ( output ) #<------ change here
Also got rid of your inside print statement since it's not your output.

Python 3 - Check if digit inside a number with if comprehension

This currently works for what I'm trying to do (where 'i' is the number I'm checking to see if it is in the 'digit'):
if str(digit) in str(i):
count += 1
However, when I try to use an if comprehension I get an invalid syntax:
count = [count + 1 if str(digit) in str(i)]
I've tried it several different ways using just [count +=1 if...] and count = [count + 1 if...]
Can anyone provide some insight into this issue?
There currently is nothing wrong with the way you are doing it now. Just want to point that out. If you are simply trying to do this in one line, maybe this solution is what you are looking for.
But to answer your comprehension issue:
You have two problems going on here that I'd like to point out.
You should not check if you have a digit in your string by trying to cast it to str. Simply use isdigit against the character you are checking.
You cannot use a comprehension the way you are trying to use it. What you have to understand about a comprehension, is that you are creating a new list and taking that new list and assigning it to a variable (in your case count). So doing this:
count = [count + 1....]
Really does not make much sense to do.
What you should do instead if you are looking to do this in a comprehension,
Iterate over each character in a, for each character, check if it is a digit:
[c.isdigit() for c in a]
Now, with that above part done. You will have a list of 1s for all digits in your word. The next step is to sum everything together. Now, the extra bit of information to pay attention to, is that when calling sum on this, we will lose the square brackets, because we will instead use what is called a generator expression.
So, with all that said and done. Your final solution is:
a = "fjf7jjjf77773jf3j"
print(sum(c.isdigit() for c in a))
# outputs 7
List comprehension (with square brackets) is used to generate list. But, in your case, you are not really generating any list. However, if you are trying to write an inline if, try -
count = count + 1 if str(digit) in str(i) else count
You can just sum the boolean value from character.isdigit() where character is each character in the string.
Consider:
>>> s='abc123def456'
>>> [c.isdigit() for c in s]
[False, False, False, True, True, True, False, False, False, True, True, True]
>>> sum(c.isdigit() for c in s)
6
I'm not sure why you would want to get a list in this case because in your first example, you simply incremented an integer variable called count. If you're looking for something more nuanced, you could try using a function like this:
def count_letter_instance(string="", letter=""):
return sum([1 for x in string if x == letter])
print(count_letter_instance("hello hello hello", "h"))
print(count_letter_instance("cat cat cat", "c"))
Output:
3
3

Subscripting an Array of Integers in Python?

I'm absolutely terrible at Python and my Computer Programming class ends in two days (thank god), but I am having the hardest time figuring out what is probably the easiest code ever.
The instructions to my assignment state, "Write a program which reads in text until a '!' is found. Use an array of integers subscripted by the letters 'A' through 'Z'."
From what i have done so far:
msg = input("What is your message? ")
msg = msg.upper()
int_array = [0] * 26
for alph in range (65, 91):
char = chr(alph)
print(char)
(int_array[char])
any help would be greatly appreciated! thanks!
EDIT: This is the full assignment:
Write a program which reads in text from the keyboard until a ('!') is found.
Using an array of integers subscripted by the letters 'A' through 'Z', count the number occurrences of each letter (regardless of whether it is upper or lower case). In a separate counter, also count the total number of "other" characters ('.', '?', ' ', '2', etc.).
Print out the count for each letter found. Also, print the count of the non-letter characters.
By inspecting the array, print out the count of the number of vowels, and the number of consonants.
Print out which letter was found the most times. (Note there may be more than one letter which has the maximum count attached to it.) Print out which letter (or letters) was found the least number of times, but make certain to exclude letters which were not found at all.
UPDATE:
I have gotten this far with my code
msg = input("What is your message? ")
print ()
num_alpha = 26
int_array = [0] * num_alpha
for alpha in range(num_alpha):
int_array[alpha] = chr(alpha + 65)
print(int_array[alpha], end = "")
print()
lett = 0
otherch = 0
num_vowels = 0
num_consanants = 0
count_character = [0] * 100000
length = len(msg)
for character in msg.upper():
if character == "!":
print("lett =", lett)
print("other char = ", otherch)
print("num_vowels = ", num_vowels)
print("num_consanants = ", num_consanants)
elif character < "A" or letter > "Z":
otherch = otherch + 1
count_character[ord(character)] = count_character[ord(character)] + 1
else:
lett = lett + 1
count_character[ord(character)] = count_character[ord(character)] + 1
for character in msg:
print("character", character, "appeared" , count_character[ord(character)] , "times")
it's obviously not finished yet, but every time i print the last print statement, it says that each character appeared 0 times. can anybody help?
You're going to need to get clarification on this, because there's no such thing as "an array of integers subscripted by the letters 'A' through 'Z'" in Python.
Possible interpretations that I can think of:
It's supposed to be a dictionary rather than an array. Python dictionaries are similar to lists (the Python datatype that is roughly equivalent to "arrays" in other languages), but they can be subscripted by strings, whereas lists can be subscripted only by integers. This way, you can store an integer to be associated with each letter. This is how most Python programmers would generally do something like this.
You're supposed to use parallel lists. You can do this by making two lists of 26 elements each, one containing the letters 'A' through 'Z' and one containing integers. For each letter, you could then use the list.index method to find the index in the first list where that letter is, then look up that index in the second list. (In theory, you wouldn't really need the first list, since Python strings are like lists in that they can be subscripted with integers and support the index method. So you could use the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' instead of a list. Or you could use the ord function, which is the inverse of the chr function. But I don't know if you're supposed to use these features.)
I'm not 100% sure the following is right because I agree with the others that the assignment description is wonky. It looks like a C-based homework assignment lazily ported to Python. That said:
In principle rather than hardcoding the bounds of the alphabet I'd go with ord('A') and ord('Z')+1, so that I can say something like alphabet = list(range(ord('A'), ord('Z')+1))
Renaming int_array to counter might make it more obvious what you need to do in your inner loop (keeping in mind that you're using the letters as your indices. Or rather, you'd need something more like ord(letter)-ord('A') as your indices)
You don't want to loop over the alphabet; you want to loop over the input.
count should be initialized to [0]*27 to track "other" values. You can increment counter[-1] for non-alphabetic characters.
Your final value is chr of counter.index(max(counter)). You may find it more straightforward, or your teacher may find it more acceptable, to just write a for loop.

Categories

Resources