Python Forum
a better way of writing code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a better way of writing code
#1
Hi is there a better way of writing this code instead of writing the repetitive multiple if statements? I'm trying to find a better way of writing this code. Basically I want to count up the the total number of matching letters in the given string s.

s = 'abcdbobbobbegkhl'
count = 0
for letter in s:
    if letter == 'a':
        count += 1
    if letter == 'e':
        count += 1
    if letter == 'i':
        count += 1
    if letter == 'o':
        count += 1
    if letter == 'u':
        count += 1
print('Number of vowels: ' + str(count))
Reply
#2
count = 0
for letter in s:
    if letter in ('aeiou'):
        count += 1
print('Number of vowels: ' + str(count))
Output:
Number of vowels: 4

count = sum(s.count(letter) for letter in ('aeiou'))
print(f'Number of vowels: {count}')
Output:
Number of vowels: 4

import collections

letter_count = collections.Counter(s)
count = sum(letter_count[letter] for letter in ('aeiou'))
print(f'Number of vowels: {count}')
Output:
Number of vowels: 4
Reply
#3
s = 'abcdbobbobbegkhl'
vowels = 'aeiou'
vowel_count = 0
for letter in s:
    if letter in vowels:
        vowel_count += 1
print(f'Number of vowels: {vowel_count}')
s = 'abcdbobbobbegkhl'
vowels = 'aeiou'
vowel_count = len([letter for letter in s if letter in vowels])
#vowel_count = sum([1 for letter in s if letter in vowels])
print(f'Number of vowels: {vowel_count}')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
import re
s = 'abcdbobbobbegkhl'
count = len(re.findall(r"[aeiou]", s))
Reply
#5
>>> s = 'abcdbobbobbegkhl'
>>> sum(map(s.count, 'aeiou'))
4
Reply
#6
Here's my preferred solution:
vowels = set("aeiou")
sum(char in vowels for char in s)
This takes advantage of Python letting you sum() booleans. I think it reads like English and is Pythonic. (In a larger program, I'd probably name VOWELS as a constant.)

I avoid some particular things for some particular reasons...

I avoided count() because it has to be called for each vowel, causing a multiplication when calculating such algoritms' runtimes. I used a set because they're constant-time lookup, and usually fast; if I really cared about the speed, I'd test to see if a linear search through the string is faster. And if my manager has told me to speed it up I'd check tuples too :)

I avoid map() in Python because I think comprehensions are clearer, and because I think map() should be a method rather than a global function. (This is one place Scala beats Python in my mind. In Python, nesting comprehensions or map calls sucks. But collection.map(foo).map(bar).map(baz) can be spread across multiple lines nicely, if the functions are are defined in-line.)

I avoided len() because it requires creating an intermediate collection. sum() can be passed a generator expression which uses constant-time memory.
Reply
#7
s = 'abcdbobbobbegkhl'
count = len([x for x in s if x in 'aeiou'])
print(f"There are {count} vowels in the string")
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  writing and running code in vscode without saving it akbarza 1 376 Jan-11-2024, 02:59 PM
Last Post: deanhystad
  Help with writing or plan part of code Merlin_1 1 1,802 Aug-24-2020, 03:28 AM
Last Post: Larz60+
  Writing a basic shift code djwilson0495 2 2,249 Aug-16-2020, 01:52 PM
Last Post: djwilson0495
  code not writing to projNameVal portion of code. umkc1 1 1,662 Feb-05-2020, 10:05 PM
Last Post: Larz60+
  C API: Writing Executed Code to a File myanrueller 0 1,696 Nov-17-2019, 09:35 PM
Last Post: myanrueller
  i am getting error while writing code for exception logging rkgupta51179 1 1,831 Nov-03-2019, 05:12 AM
Last Post: buran
  Writing a code with 3 digit numbers while they cant contain 0 and then sum them AFKManager 2 2,370 Jan-13-2019, 12:00 PM
Last Post: perfringo
  Help with Code (Writing Data File) caroline_d_124 3 2,843 Jan-06-2019, 09:17 PM
Last Post: caroline_d_124
  Help writing code to create a ranked list swilson421 2 2,446 Jul-16-2018, 04:51 PM
Last Post: swilson421
  Need help writing simple code isashay 7 6,115 Mar-13-2018, 12:26 AM
Last Post: isashay

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020