How to count words that end with a letter? (python) - python

I am a beginner and this is what I came up with so far. However, it does not output the correct number of words that end with "a" or "b." Any tips on how to correct this code?
names = input("Enter list of names: ")
name = names.split(" ")
num = len(name)
ab = ""
print("Number of words:", num)
for i in range(num):
if name[i] == ' ':
if name[i-1] == a:
ab.append() + " "
elif name[i-1] == b:
ab.append() + " "
a_b = ab.split(' ')
print("Number of words that end with a or b: ",len(a_b))

In Python boolean (True and False) are the same as the integers 1 and 0. This means you can use sum() to count True booleans. str.endswith() returns a boolean. This means you can just do this:
words = ["stab", "drama", "hello", "magma", "test"]
a_b = sum(word.endswith(('a', 'b')) for word in words)
# 3
z_c = sum(word.endswith(('z', 'c')) for word in words)
# 0

Any tips on how to correct this code?
Others have answered alternative, working solutions, but I want to try to point out the specific things wrong in your code snippet and tips to correct.
First here's a copy of your snippet with some simple debugging prints along with their output (running in python 3.10).
names = "Barry Lima Bab"
name = names.split(" ")
print(f"{name=}") # name=['Barry', 'Lima', 'Bab']
num = len(name)
print(f"{num=}") # num=3
ab = ""
print("Number of words:", num)
for i in range(num):
print(name[i]) # Barry -> Lima -> Bab
if name[i] == ' ':
if name[i-1] == a:
ab.append() + " "
elif name[i-1] == b:
ab.append() + " "
print(f"{ab=}") # ab=''
a_b = ab.split(' ')
print(f"{a_b=}") # a_b=['']
Breaking things down step by step like this is a great starting point for better understanding what's going on.
if name[i] == ' ': Notice the value of name[i] so this check never resolves to True meaning the code inside never runs
if the inner code did run, you'd hit a NameError: name 'a' is not defined. Did you mean: 'ab'? because a is undefined. Probably meant 'a' here. same for b
In my example, name[i-1] would be 'Bab' -> 'Barry' -> 'Lima' which is probably not what you're expecting. This is because you're getting the -1th, 0th, 1st items in name. to get the last letter from the name, you want name[i][-1] here
if you then get into either of the furthest inside conditions, you'd encounter AttributeError: 'str' object has no attribute 'append' which happens because append is for list not str. You couldchange ab to be a list to use this in which case you'd want ab.append(name[i]) or you can use string concatenation like ab += " " + name[i] or using str.concat
1 last note of interest, you may have noticed your code as-is really likes to return and say that there's 1 item. This is because the above issues always (if the program doesn't break) leaves ab == '' and ''.split(' ') => [''] and thus len(ab.split(" ")) => 1
1 tip that I think would help in code comprehension is that the name variable here is not a single name string like it implies. It's actually a list[str]. I'd probably denote the variables something more like names_str: str vs names: list[str] or raw_names vs names. Then just use something like for name in names: and not worry about indexes. You can also use name.endswith('a') instead of name[-1] == 'a' for better readability.
Eventually you can combine these into a list comprehension for maximal succinctness -> len([name for name in names if name.endswith('a') or name.endswith('b')]).

words = ["ab", "bab", "pa", "pap"]
result = 0
for word in words:
if word[-1] in "ab":
result += 1
print(result)

As a list comprehension:
words = ["word1a", "word2b", "word3", "word4", "word5a"] # ['word1a', 'word2b', 'word5a']
filtered_words = [word for word in words if word[-1] in "ab"]
filtered_words = [word for word in words if word.endswith(("a", "b"))] # better, if you have multiple endings you want to search for with different lengths
len(filtered_words) # 3

name[i-1] is the previous name in the list, not the last character of the current name in the loop.
There's no need to append the matching names to a string. If you just need the count of matches, increment a counter variable.
You need to put a and b in quotes to make them strings, not variables.
names = input("Enter list of names: ")
name = names.split(" ")
matches = 0
print("Number of words:", len(name))
for cur_name in name:
if cur_name.endswith('a') or cur_name.endswith('b'):
matches += 1
print("Number of words that end with a or b: ", matches)

Use the endswith string method to detect if the last letter is "a" or "b"
names = ["bob","boba","larry","curly","moe"]
count = 0
for name in names:
if name.endswith("a") or name.endswith("b"):
count += 1
print(f"{count=}") # count=2

Related

a function that prints the second word of any sentence i have a probleme when a string is like "ghanou djellal"it returns nothing [duplicate]

This question already has answers here:
Python: replace nth word in string
(5 answers)
Closed 1 year ago.
# Strip function remove the whitespaces from the start and the end of the string.
a = str(input("Enter Your String : ").strip())
the function that returns the second element
def second_word(a):
b = 0
c = a.split(" ")
while b < len(c):
if c[b] == "" and c[b+1] != "":
print(f" Your Second Word Is :{c[b+1]}")
break
b += 1
second_word(a)
You can do it much easier if you use the split() methode and print the second element (index 1) of the list.
def secondword(sentence):
listofwords = sentence.split(" ")
return listofwords[1]
print(secondword("My name is"))
The condition c[b] == "" will never hold, unless the original string is "".
c is a list. In order to access its second element you would do c[1].
def second_word(a):
c = a.split(" ")
print(f" Your Second Word Is :{c[1]}")
second_word(a)
Should you simply do:
def second_word(a):
return a.split()[1]
If you want to write a function along the logic you proposed (well - this is not advised - but just to articulate on what you tried to do):
def second_word(a):
start = 0
for i, l in enumerate(a):
if l == " ":
if start == 0:
start = i
else:
print("You second word is: " + a[start:i].strip())
break

Hacker rank string separated challenge

I'm trying to solve a hacker rank challenge:
Given a string, s , of length n that is indexed from 0 to n-1 , print its even-indexed and odd-indexed characters as 2 space-separated strings. on a single line (see the Sample below for more detail)
link: https://www.hackerrank.com/challenges/30-review-loop/problem
Error:
for example:
The input "adbecf" should output "abc def"
When I run python Visualizer my code seem to have the correct output.. but on hacker rank it's saying I have the wrong answer. Does anyone know what might be wrong with my code.
This is the code I tried -
class OddEven:
def __init__(self, input_statement):
self.user_input = input_statement
def user_list(self):
main_list = list(user_input)
even = []
odd = []
space = [" "]
for i in range(len(main_list)):
if (i%2) == 0:
even.append(main_list[i])
else:
odd.append(main_list[i])
full_string = even + space + odd
return(full_string)
def listToString(self):
my_string = self.user_list()
return(''.join(my_string))
if __name__ == "__main__":
user_input = str(input ())
p = OddEven(user_input)
print(p.listToString())
First of all, input is always string, you don't need to convert it here.
user_input = str(input())
Each line is provided to you as separate input. Number of strings equal to num in the first line. In this case 2, so...
count = input()
for s in range(int(count)):
...
user_input variable inside user_list function should be accessed as self.user_input, it's a property of an object, which you pass to function as self.
Also you can iterate over list directly.
Here:
full_string = even + space + odd
you're trying to concatenate list, which is not a good idea, you'll still get a list.
You can join list with separating them with some string using join string method.
' '.join(list1, list2, ..., listN)
It's better do define odd and even as empty strings.
And then join them the using concatenation (+).
Here:
if (i%2) == 0
you don't have to compare with 0. Python will evaluate what's to the right from condition as True or False. So:
if i % 2:
...
There is simpler solution:
def divide(self):
odd = even = ''
for i, c in enumerate(self.user_input):
if i % 2:
odd += c
else:
even += c
return even + ' ' + odd
Here is the simple code for this problem:)
T=int(input())
for i in range(0,T):
S=input()
print(S[0::2],S[1::2])

python str object does not support item assignment

I'm trying to set the scrambled word from the list back to the list I have created, which is from split. I tried reading some of the solutions here and I think it's because you can't change the string in the list?
I'm not really sure correct me if I'm wrong :( . the sentence[i] = temp_word is giving the error. thanks in advance :)
class WordScramble:
def __init__(self):
self.user_input = input("Please give me a sentence: ")
def scramble(self):
# print what was input
print("The user input was: ", self.user_input)
# first scramble is just one word
print(self.user_input[0] + self.user_input[2] + self.user_input[1] + self.user_input[3:])
# reverse two indices
# particularly good to use is to switch the first two
# and the last two
# this only makes sense if you have a world that is longer than 3
# now try to scramble one sentence
sentence = self.user_input.strip().split(" ")
for i, word in enumerate(sentence):
if len(word) > 3:
temp_word = list(word)
if ',' in temp_word:
temp = temp_word[1]
temp_word[1] = temp_word[-3]
temp_word[-3] = temp
else:
temp = temp_word[1]
temp_word[1] = temp_word[2]
temp_word[2] = temp
temp_word = ''.join(temp_word)
sentence[i] = temp_word
sentence = ''.join(sentence)
print(sentence)
#print(" ".join(sentence))
# do just words first, then you can move on to work on
# punctuation
word_scrambler = WordScramble()
word_scrambler.scramble()
Because inside the for loop you wrote:
sentence = ''.join(sentence)
Thus, at the second iteration, the 'sentence' variable is now a string and in python, strings don't support item assignment as they are immutable variables. I think you meant to get this out of the for loop to print the final sentence.

Python Case Matching Input and Output

I'm doing the pig latin question that I'm sure everyone here is familiar with it. The only thing I can't seem to get is matching the case of the input and output. For example, when the user enters Latin, my code produces atinLay. I want it to produce Atinlay.
import string
punct = string.punctuation
punct += ' '
vowel = 'aeiouyAEIOUY'
consonant = 'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ'
final_word = input("Please enter a single word. ")
first_letter = final_word[:1]
index = 0
if any((p in punct) for p in final_word):
print("You did not enter a single word!")
else:
while index < len(final_word) and (not final_word[index] in vowel):
index = index+1
if any((f in vowel) for f in first_letter):
print(final_word + 'yay')
elif index < len(final_word):
print(final_word[index:]+final_word[:index]+'ay')
What you need is str.title(). Once you have done your piglatin conversion, you can use title() built-in function to produce the desired output, like so:
>>> "atinLay".title()
'Atinlay'
To check if a string is lower case, you can use str.islower(). Take a peek at the docs.
simply use the built in string functions.
s = "Hello".lower()
s == "hello"
s = "hello".upper()
s == "HELLO"
s = "elloHay".title()
s == "Ellohay"

Python: print specific character from string

How do I print a specific character from a string in Python? I am still learning and now trying to make a hangman like program. The idea is that the user enters one character, and if it is in the word, the word will be printed with all the undiscovered letters as "-".
I am not asking for a way to make my idea/code of the whole project better, just a way to, as i said, print that one specific character of the string.
print(yourstring[characterposition])
Example
print("foobar"[3])
prints the letter b
EDIT:
mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
if mystring[c] == lookingfor:
print(str(c) + " " + mystring[c]);
Outputs:
2 l
3 l
9 l
And more along the lines of hangman:
mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
if mystring[c] == lookingfor:
print(mystring[c], end="")
elif mystring[c] == " ":
print(" ", end="")
else:
print("-", end="")
produces
--ll- ---l-
all you need to do is add brackets with the char number to the end of the name of the string you want to print, i.e.
text="hello"
print(text[0])
print(text[2])
print(text[1])
returns:
h
l
e
Well if you know the character you want to search you can use this approach.
i = character looking for
input1 = string
if i in input1:
print(i)
you can change the print statement according to your logic.
name = "premier league"
for x in name:
print(x)
Result shown below:-
To print specific characters of the given string. For example to print 'l' from the given string
name = "premier league"
for x in name:
if x == "l":
print("element found: "+x)

Categories

Resources