Question

he final function of this problem does not require the use of either recursion or a...

he final function of this problem does not require the use of either recursion or a list comprension. Rather, it will allow you to practice using conditional logic and variable assignment to gradually build up a return value.

  1. Write a function price_string(cents) that takes as input a positive integer cents representing a price given in cents, and that constructs and returns a string in which the price is expressed as a combination of dollars and cents.

    In general, the format of the returned string should be 'd dollars, c cents', where d is the whole number of dollars in the price and c is the remaining cents. For example:

    >>> price_string(452)
    result: '4 dollars, 52 cents'
    
    >>> price_string(871)
    result: '8 dollars, 71 cents'
    

    However, there are two additional rules that you must observe:

    • If either component of the price is 0, it should be omitted:

      >>> price_string(27)
      result: '27 cents'
      
      >>> price_string(300)
      result: '3 dollars'
      

      (Because we assume that the input cents is positive, it will never be the case that both of the components are 0!)

    • If either component of the price is 1, you should omit the 's' from the word for that component:

      >>> price_string(201)
      result: '2 dollars, 1 cent'
      
      >>> price_string(117)
      result: '1 dollar, 17 cents'
      
      >>> price_string(101)
      result: '1 dollar, 1 cent'
      

Important Guidelines

  • You must begin by copying the following template into your file:

    def price_string(cents):
        """ docstring goes here """
        d = _______________   # compute whole number of dollars
        c = _______________   # compute remaining cents
    
        price = ''            # initial value of the price string
    
        ## add code below to build up the price string
    
        return price
    
  • Begin by replacing the two blanks with expressions that will compute the values of d (the whole number of dollars) and c (the remaining cents), based on the value of the parameter cents.

  • Next, add code to determine the appropriate value of the variable price, which is the string that the function will return. We have given you a line assigns an empty string to price as its initial value. You should use conditional execution and string concatenation to gradually build up the final value of this variable. You will need to use assignment statements that look like this:

    price = price + ...
    
  • You can use the built-in str() function to turn numbers into strings. For example, str(d) will turn the number represented by the variable d into a string.

  • Your function must limit itself to the single return statement that we have given you at the very end of the function. You will lose points if you use more than one return statement in this function.

Homework Answers

Answer #1
def price_string(cents):
    """ docstring goes here """
    d = cents // 100  # compute whole number of dollars
    c = cents % 100  # compute remaining cents

    price = ''  # initial value of the price string
    if d == 1:
        if c == 0:
            price = '1 dollar'
        elif c == 1:
            price = '1 dollar, 1 cent'
        else:
            price = '1 dollar, ' + str(c) + ' cents'
    elif d == 0:
        if c == 1:
            price = '1 cent'
        elif c > 1:
            price = str(c) + ' cents'
    else:
        if c == 0:
            price = str(d) + ' dollars'
        elif c == 1:
            price = str(d) + ' dollars, 1 cent'
        else:
            price = str(d) + ' dollars, ' + str(c) + ' cents'
    return price


print(price_string(452))
print(price_string(871))
print(price_string(27))
print(price_string(300))
print(price_string(201))
print(price_string(117))
print(price_string(101))

Know the answer?
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
Similar Questions
Use python x is a list of strings. For example, x = [’python is cool’, ’pythom...
Use python x is a list of strings. For example, x = [’python is cool’, ’pythom is a large heavy-bodied snake’, ’The python course is worse taking’] In the example, there is totally 1 occurrence of the word ’python’ (case sensitive) in the strings whose length are more than 20 in the list x. In order to count the number of occurrences of a certain word str in the strings which are long enough, use filter and reduce and write...
In Python: This will require you to write several functions, and then use them in a...
In Python: This will require you to write several functions, and then use them in a program. Logical Calculator The logical calculator does math, but with logical operators. In logic, we represent a bit with 0 as false and a bit with 1 as true. The logical operators are NOT, AND and OR. Bitwise logical calculations operate on each bit of the input. The NOT operator works on just one three-bit argument. NOT 011 = 100 The AND operator works...
Complete a function definition in C for strmatch. For this problem, you can't use any <string.h>...
Complete a function definition in C for strmatch. For this problem, you can't use any <string.h> library functions. In c, two strings match exactly if they have the same characters in the same order and same length. Consider this: int strmatch(const char *x, const char *b); //Needs each of x and y points to the beginning of a string. //Promises to return value 1 if the two strings match exactly. If they don't match, the return value is 0. For...
I am to create three different versions of the following C program code below that implements...
I am to create three different versions of the following C program code below that implements the conversion of unsigned binary numbers into decimal (Base 2 to Base 10 conversion). Version 1: Complete the C program ”bin2dec ver1.c” that implements binary to decimal conversion. The maximum number of binary bits is 32. The program is made of the functions ”unsigned binary to decimal(const char *str)”and ”main”. The parameter ”str” passed to this function points to a C string comprising only...
1. Write 3n + 1 Sequence String Generator function (1 point) In lab5.py complete the function...
1. Write 3n + 1 Sequence String Generator function (1 point) In lab5.py complete the function sequence that takes one parameter: n, which is the initial value of a sequence of integers. The 3n + 1 sequence starts with an integer, n in this case, wherein each successive integer of the sequence is calculated based on these rules: 1. If the current value of n is odd, then the next number in the sequence is three times the current number...
USE C programming (pls label which file is libcipher.h and libcipher.c) Q4) A shift cipher is...
USE C programming (pls label which file is libcipher.h and libcipher.c) Q4) A shift cipher is one of the simplest encryption techniques in the field of cryptography. It is a cipher in which each letter in a plain text message is replaced by a letter some fixed number of positions up the alphabet (i.e., by right shifting the alphabetic characters in the plain text message). For example, with a right shift of 2, ’A’ is replaced by ’C’, ’B’ is...
in C++ Write a program. The program should prompt the user for the number of shares...
in C++ Write a program. The program should prompt the user for the number of shares purchased, purchase price per share, the commission for the purchase, sale commission paid, and the price the shares were sold at. The program should validate each of these values to ensure they are acceptable (none can be less than zero) and should then pass them to a function called numberfunction.The function should use the following formula to determine the profit: Profit = ((number of...
The number of baskets (either team) in a NBA basketball game is modeled using a Poisson...
The number of baskets (either team) in a NBA basketball game is modeled using a Poisson process with rate 1.5 per minute. (a) What is the distribution for the number of baskets in the first quarter (12 minutes)? Write down the pmf. (b) What is the distribution for the number of baskets in the whole game (assume game length of 48 minutes, i.e. 12 minutes per quarter)? Write down the pmf. (c) Write down the formula for the probability that...
1. In a separate JS file, write a function to calculate gross wages for an hourly...
1. In a separate JS file, write a function to calculate gross wages for an hourly employee. The function should receive two parameters: the pay rate (dollars per hour, a floating point number) and the hours worked. Hours from 0 through 40 are “straight time” pay, and any hours in excess of 40 are overtime pay at 1.5 times the standard rate (hint: use the ? : operator to make a decision about pay rates). The function should return a...
Use Rstudio to create a script by following the instruction below. I've created the first question...
Use Rstudio to create a script by following the instruction below. I've created the first question code but I can not continue it further. Thank you. ## Write a function called `make_introduction` that takes in two arguments: name, and age. ## This function should return a string value that says something like "Hello, my name is {name}, and I'm ## {age} years old". make_introduction <- function(name, age){ print(paste("Hello, my name is", name, "and I'm", age, "years old")) } ## Create...