Home > Software design >  Python - count the number of letter U's and return the line that contains them
Python - count the number of letter U's and return the line that contains them

Time:03-18

My professor wants us to create a program that will allow multiple lines of input from a user and determine which line has the most amount of the letter U. We then need to print the count and the line. Example of input:

This u is u an u example u line.
This u is another.
Example u line u.

Example of output:

Line with the most U's: 4
This u is u an u exammple u line.

I have this so far for the count but I am completely stuck on how to get it to go line by line.

#input line was provided by professor - not needed
def count_letter_u(line):
  count = 0
  for ch in line:
    if ch == 'u':
      count  = 1
  return count

CodePudding user response:

I am not sure how you are getting multiple lines as input so I wrote my own way of getting multiple lines as input

print("Enter your content, Ctrl-D and Enter to save it.") 
contents = [] 
dict = {}
while True: 
    try: 
        line = input() 
    except EOFError: 
        break 
    contents.append(line)

def count_letter_u(line):
  count = 0
  for ch in line:
    if ch == 'u':
      count  = 1
  return count

for sentence in contents:
  dict[sentence] = count_letter_u(sentence)

max = max(zip(dict.values(), dict.keys()))[1]

print(f"Line with the most U's: {dict.get(max)}, {max}")

Output

Enter your content, Ctrl-D and Enter to save it.
This u is u an u example u line.
This u is another.
Example u line u.
Line with the most U's: 4, This u is u an u example u line.

contents is the list of sentences

CodePudding user response:

You can use splitLines() function to split the lines first. (Assuming that your professor gives you all the lines as a single string).

Then use the count_letter_u function to get the number of us.

def get_lines(text):
  lines = text.splitLines()
  for line in lines:
    u_count = count_letter_u(line)

def count_letter_u(line):
  count = 0
  for ch in line:
    if ch == 'u':
      count  = 1
  return count

CodePudding user response:


input_string = "This u is u an u example u line.\nThis u is another.\nExample u line u."
lines = input_string.splitlines()  #splitting the string in lines

most_u = -1                        # most 'U' count (since a line may have 0 'U' but not -1 so ) will be greater)
index_with_most_u = -1             # index (number) of line which has most 'U'

def count_letter_u(line):
  count = 0
  for ch in line:
    if ch == 'u':
      count  = 1
  return count

for index,line in enumerate(lines):
    if most_u < count_letter_u(line): # If we find greater number of U till this point we update the most_u and line number
        most_u = count_letter_u(line)
        index_with_most_u = index
        
print("Line with the most U's:"   str(most_u))
print(lines[index_with_most_u])
  • Related