Question

In: Computer Science

In Python I have a code: here's my problem, and below it is my code. Below...

In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist.

Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same.

Examples:

swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER'

swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I HOPE MY CAPS LOCK DOES NOT GET STUCK ON'

#code:

def swapCaps(val):
res="" #res string to store altered string
for i in val: #iterarte through each char
    if i.isupper(): #if present char is upper case
      res=res+i.lower() #make it lower case can concate it to result string
    elif i.islower():#if present char is lower case
      res=res+i.upper() #make it upper case can concate it to result string
    elif i==' ': #if present char is space
      res=res+i #conbcate it as it is
return res #return result

#driver program to test
val='Hope you are all enjoying October'
print(swapCaps(val))
print(swapCaps( 'i hope my caps lock does not get stuck on' ) )

#error:

Failed tests

Symbols

If you completed the first two but failed this one you probably did not account for symbols being in the sentence. They should remain unchanged. The test was "H@lloween W!ll Sc@re You @s Much @s This Test C@se!" should result in "h@LLOWEEN w!LL sC@RE yOU @S mUCH @S tHIS tEST c@SE!"

More info

Traceback (most recent call last): File "/home/runner/unit_tests.py", line 24, in test_Symbols self.assertEquals(swapCaps("H@lloween W!ll Sc@re You @s Much @s This Test C@se!"), "h@LLOWEEN w!LL sC@RE yOU @S mUCH @S tHIS tEST c@SE!") AssertionError: 'hLLOWEEN wLL sCRE yOU S mUCH S tHIS tEST cSE' != 'h@LLOWEEN w!LL sC@RE yOU @S mUCH @S tHIS tEST c@SE!' - hLLOWEEN wLL sCRE yOU S mUCH S tHIS tEST cSE + h@LLOWEEN w!LL sC@RE yOU @S mUCH @S tHIS tEST c@SE! ? + + + + + + +

Solutions

Expert Solution

Changed code:

def swapCaps(val):
    res="" #res string to store altered string
    for i in val: #iterarte through each char
        if i.isalpha(): # check if character is alphabet or not
            if i.isupper(): #if present char is upper case
              res=res+i.lower() #make it lower case can concate it to result string
            else: #else the present char is lower case
              res=res+i.upper() #make it upper case can concate it to result string
        else: # if character is not alphabet then we directly append it to our result
            res=res+i

    return res #return result

#driver program to test
val='Hope you are all enjoying October'
print(swapCaps(val))
print(swapCaps( 'i hope my caps lock does not get stuck on' ) )
print(swapCaps( 'H@lloween W!ll Sc@re You @s Much @s This Test C@se!' ) )

Screenshot of the code to get the ordering which is important in python:

Output:

Explaination:

The main change in the code is if i.isalpha() which is a function is python which return true if the string/character is only alphabets. In this case we just used it for checking characters and not string as whole.

So if i.isalpha() is true then we check if i.isupper() which checks if the character is uppercase or not. If it is uppercase then we change it to lowercase and append to the result. If the character is not uppercase then we move to else. The reason for changing elif is there is no use for elif. Firstly we have added a if which check if character is alphabet or not so if it is an alphabet then it can only be uppercase or lowercase. So if uppercase is not true then it will be lowercase and then we will change it to uppercase.

In the main else part of i.isalpha() we will directly append it to the result. The contents can be special characters like @, ! or anything also it can be numbers like 1,2.. and it can also be a space which is also a character


Related Solutions

This is the code I have. My problem is my output includes ", 0" at the...
This is the code I have. My problem is my output includes ", 0" at the end and I want to exclude that. // File: main.cpp /*---------- BEGIN - DO NOT EDIT CODE ----------*/ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> using namespace std; using index_t = int; using num_count_t = int; using isConnected_t = bool; using sum_t = int; const int MAX_SIZE = 100; // Global variable to be used to count the recursive calls. int recursiveCount =...
I have an unexpected indent with my python code. please find out whats wrong with my...
I have an unexpected indent with my python code. please find out whats wrong with my code and run it to show that it works here is the code : def main(): lis = inputData() customerType = convertAcct2String(lis[0]) bushCost = getBushCost(lis[0],int(lis[1],10)) flowerCost = getFlowerBedCost(int(lis[2],10),int(lis[3],10)) fertiCost = getFertilCost(int(lis[4],10)) totalCost = calculateBill(bushCost,fertiCost,flowerCost) printReciept(customerType,totalCost,bushCost,fertiCost,flowerCost) def inputData(): account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage = input("Please enter values").split() return [account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage] def convertAcct2String(accountType): if accountType== "P": return "Preferred" elif accountType == "R": return "Regular" elif accountType == "N": return...
Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
What's wrong with my Python code. We have to find the regularexpression in Python My output...
What's wrong with my Python code. We have to find the regularexpression in Python My output should look like this My IP address 128. 0. 0. 1 My IP address 53. 20. 62. 201 My code ipAddresses = [] ipRegEx = re.compile(r"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")    result = myRegEx.find all(Search Text)    def Regular_expression(ipAddresses)       for i in ipAddresses:          print(i) ipSearchResult = ipRegEx.search(line)    if ipSearchResult != None and ipSearchResult.group() not in ipAddresses:       ipAddresses.append(ipSearchResult.group()) we have to use loop too.
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
(Python) This is my code for printing a roster for a team. When I print to...
(Python) This is my code for printing a roster for a team. When I print to the console, it makes the first player's name show up as number 2, and it says [] (its just blank for 1). How can I fix that so the first player's name is 1, not skipping 1 and going to 2. def file_to_dictionary(rosterFile): myDictionary={} myDict=[]    with open(rosterFile,'r') as f: for line in f:    (num,first,last,position)=line.split() myDictionary[num]= myDict myDict=[first, last, position] print (myDictionary) return...
In Java, please write a tester code. Here's my code: public class Bicycle {     public...
In Java, please write a tester code. Here's my code: public class Bicycle {     public int cadence; public int gear;   public int speed;     public Bicycle(int startCadence, int startSpeed, int startGear) {         gear = startGear;   cadence = startCadence; speed = startSpeed;     }     public void setCadence(int newValue) {         cadence = newValue;     }     public void setGear(int newValue) {         gear = newValue;     }     public void applyBrake(int decrement) {         speed -= decrement;    ...
Need this in C#. Below is my code for Problem 3 of Assignment 2. Just have...
Need this in C#. Below is my code for Problem 3 of Assignment 2. Just have to add the below requirement of calculating the expected winning probability of VCU. Revisit the program you developed for Problem 3 of Assignment 2. Now your program must calculate the expected winning probability of VCU through simulation. Run the simulation 10,000 times (i.e., play the games 10,000 times) and count the number of wins by VCU. And then, calculate the winning probability by using...
The programming language that is being used here is JAVA, below I have my code that...
The programming language that is being used here is JAVA, below I have my code that is supposed to fulfill the TO-DO's of each segment. This code in particular has not passed 3 specific tests. Below the code, the tests that failed will be written in bold with what was expected and what was outputted. Please correct the mistakes that I seem to be making if you can. Thank you kindly. OverView: For this project, you will develop a game...
How do I add the information below to my current code that I have also posted...
How do I add the information below to my current code that I have also posted below. <!DOCTYPE html> <html> <!-- The author of this code is: Ikeem Mays --> <body> <header> <h1> My Grocery Site </h1> </header> <article> This is web content about a grocery store that might be in any town. The store stocks fresh produce, as well as essential grocery items. Below are category lists of products you can find in the grocery store. </article> <div class...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT