Question

Why can't I get this to display the results? def main():     try:         string =...

Why can't I get this to display the results?

def main():
    try:
        string = input('Enter a string: ')
#Set Character frequency and occurrence to 0
        character_frequency = 0
        character_occurrence = 0
#Create loop to count characters
        for character in string:
            compare = 0
            occurrence = 0
        while compare < len(string):
            if character.lower() == string[compare].lower():
                compare += 1
                occurrence += 1
        if occurrence > character_occurrence and character != '':
            character_occurrence = occurrence
            character_frequency = character
          
        print('The most frequent character in the string is: ',character_frequency)
    except IOError:
        print('File could not be found')
    except:
        print('Unexpected Error occurred')
main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1
def main():
    try:
        string = input('Enter a string: ')
        # Set Character frequency and occurrence to 0
        character_frequency = 0
        character_occurrence = 0
        # Create loop to count characters
        for character in string:
            compare = 0
            occurrence = 0
            while compare < len(string):
                if character.lower() == string[compare].lower():
                    occurrence += 1
                compare += 1
            if occurrence > character_occurrence and character != '':
                character_occurrence = occurrence
                character_frequency = character
        print('The most frequent character in the string is: ', character_frequency)
    except IOError:
        print('File could not be found')
    except:
        print('Unexpected Error occurred')


main()

Add a comment
Know the answer?
Add Answer to:
Why can't I get this to display the results? def main():     try:         string =...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Paste this code into a new file and find the errors.  The most frequent letter in the...

    Paste this code into a new file and find the errors.  The most frequent letter in the user_string is H. # Function displays the character that appears most frequently # in the string. If several characters have the same highest # frequency, displays the first character with that frequency. def main():     # Set up local variables     count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]     letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'     index = 0     frequent = 0     # Receive user input.     user_string = 'Who where what why how'     for ch...

  • Here is the UML for the class Contact -fullName : string -phoneNum: string -emailAddress : string...

    Here is the UML for the class Contact -fullName : string -phoneNum: string -emailAddress : string +Contact()                     //default constructor sets all attribute strings to “unknown”; no other constructor +setName(string name) : void +setPhone(string pn) : void +setEmail(string em) : void +getName() : string +getPhone() : string +getEmail() : string +printContact() : void         //print out the name, phone numbers and email address Create New Project Name your project: CIS247_Lab7_YourLastName. For this exercise, you may use a header file or one file...

  • Python Programming 4th Edition: Need help writing this program below. I get an error message that...

    Python Programming 4th Edition: Need help writing this program below. I get an error message that says that name is not defined when running the program below. My solution: def main(): filename = "text.txt" contents=f.read() upper_count=0 lower_count=0 digit_count=0 space_count=0 for i in contents: if i.isupper(): upper_count+=1 elif i.islower(): lower_count+=1 elif i.isdigit(): digit_count+=1 elif i.isspace(): space_count+=1 print("Upper case count in the file is",upper_count) print("Lower case count in the file is",lower_count) print("Digit count in the file is",digit_count) print("Space_count in the file is",space_count)...

  • Write a class called TemperatureFile. • The class has one data attribute: __filename • Write get...

    Write a class called TemperatureFile. • The class has one data attribute: __filename • Write getter and setter for the data attribute. • Write a “calculateAverage” function (signature below) to calculate and return average temperature of all temperatures in the file. def calculateAverage(self): • Handle possible exceptions Write a main function: • Create a file ('Temperatures.txt’) and then use “write” method to write temperature values on each line. • Create an object of the TemperaureFile with the filename (‘Temperatures.txt’) just...

  • Using python 3.6 How do I incorporate 0 or negative input to raise an error and...

    Using python 3.6 How do I incorporate 0 or negative input to raise an error and let the user try again? like <=0 #loop to check valid input option. while True: try: choice = int(input('Enter choice: ')) if choice>len(header): print("Invalid choice!! Please try again and select value either:",end=" ") for i in range(1,len(header)+1): print(i,end=",") else: break choice = int(input('\nEnter choice: ')) except ValueError as ve:print('Invalid response, You need to select the number choice from the option menu') # Catch your...

  • 1.) Write a recursive function named isPalindrome that will take a single string as an argument...

    1.) Write a recursive function named isPalindrome that will take a single string as an argument and determine if the argument is a palindrome. The function must return True if the argument is a palindrome, False otherwise. Recall that any string is a palindrome if its first and last characters are the same and the rest of it is also a palindrome (therefore, a single character is a palindrome): 2.) Consider a text file named samplestrings.txt that contains a collection...

  • I cant get this python program to read all the unique words in a file. It...

    I cant get this python program to read all the unique words in a file. It can only read the number of the unique words in a line. import re import string from collections import Counter # opens user inputted filename ".txt" and (w+) makes new and writes def main(): textname = input("Enter the file to search: ") fh = open(textname, 'r', encoding='utf-8' ) linecount = 0 wordcount = 0 count = {} print("Sumary of the", fh) for line in...

  • I'm a bit confused on how to get this program to run right. Here are the...

    I'm a bit confused on how to get this program to run right. Here are the directions: Part 1: Write a Python function called reduceWhitespace that is given a string line and returns the line with all extra whitespace characters between the words removed. For example, ‘This line has extra space characters ‘  ‘This line has extra space characters’ Function name: reduceWhitespace Number of parameters: one string line Return value: one string line The main file should handle the...

  • I dont know how to get this code working??? this is my code: # read_running_times.py #...

    I dont know how to get this code working??? this is my code: # read_running_times.py # Chapter 6.2 Page 258 def main(): # Open the video_times.txt file for reading. video_file = open('video_times.txt', 'r') # Initialize an accumulator to 0.0 total = 0.0 # Initialize a variable to keep count of the videos. count = 0 print('Here are the running times for each video:') # Get the values from the file and total them. for line in video_file: # Error 1:...

  • Pseudocode for main: Get a string from user If string has correctly matched delimiters print "All...

    Pseudocode for main: Get a string from user If string has correctly matched delimiters print "All matched correctly Pseudocode for FSM: Note: This is to be implemented as a subprogram that returns a boolean value of true or false indicating whether or not all delimiters matched correctly. State O (Starting State): .Read next character in input string . If char is open delimiter, next state is 1 lf char is close delimiter, next state is 2 . If char is...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT