Question

In: Computer Science

2.2 Decimal-to-Undecimal Exercise Assign to undecimal_str the undecimal string that represents a non-negative integer decimal of...

2.2 Decimal-to-Undecimal

Exercise Assign to undecimal_str the undecimal string that represents a non-negative integer decimal of any size.

Hint: For loop or while loop?

write the program:

def decimal_to_undecimal(decimal):
# YOUR CODE HERE

return undecimal_str

Solutions

Expert Solution

def decimal_to_undecimal(decimal):
    result = []
    while decimal > 0: 
        result.append(str(decimal % 10))
        decimal = decimal // 10 
    return ''.join(result[::-1])

print(decimal_to_undecimal(10000))
print(type(decimal_to_undecimal(10000)))

Output:

(Class 'str' means that we have outputted a string instead of a number in this case).

Explanation:

In this code, we iterate over the number digit by digit. We know that the last digit of a number can be obtained by taking the remainder of the number by 10. We can use this method to iteratively find all the digits of the number, by repeatedly dividing the number by 10, and converting each remainder to a string. We add each string converted value of the remainder to a list called result.

For a sample input 1234, here's how this would work:

1. We take remainder of 1234 with 10, we get 4. We add '4' (integer converted to string using the str() function) to the list called result. We then divide the decimal input by 10, which gives us decimal = 123. Current value of result = ['4'].

2. We take remainder of 123 with 10, we get 3 as the result. We add '3' to the list result. We divide 123 by 10, we get 12. Current value of result = ['4', '3'].

3. We take remainder of 12 with 10, we get 2 as the result. We add '2' to the list result. We divide 12 by 10, we get the value 1 as the quotient. Current value of result = ['4','3','2'].

4. We take remainder of 1 with 10, we get 1 as the result. We add '1' to the list result. We divide 1 by 10, we get the quotient 0. Current value of result = ['4','3','2','1']. The while loop does not execute again since the value of decimal has now become zero and the condition for the while loop is no longer valid.

We then use a method called ''.join(list of characters) to convert the list of characters into a string. Now, when we simply output the ''.join(result), we get the inverse of the number we intend to have - this is because we are going from the first digit being added to the result list at the end (the one with the highest power of 10), and the first digit being added to the result list right at the beginning (the one with the highest power of 10). In our example, '4' is the last digit which gets added first, and '1' is the first digit which gets added last.

Hence, for our program to work correctly, we have to reverse our list, and then use the ''.join(result) command. This can be achieved without using a for loop through each of the characters in the list, by employing the list operation with index "::-1" -> this reverses the list in place.

We show the difference between not using ::-1 and using ::-1 as follows:

Output:

Code with the list reversing syntax:

Output:

Hence, we have successfully converted a non-negative decimal value into a string.

Here's the code:

def decimal_to_undecimal(decimal):
    result = []
    while decimal > 0: 
        result.append(str(decimal % 10))
        decimal = decimal // 10 
    undecimal_str = ''.join(result[::-1])
    return undecimal_str

print(decimal_to_undecimal(987654321))

(I have changed it at the end to meet the code structure requirement as shown in the question)

If you liked this answer, please consider giving it a thumbs up. Thank you!


Related Solutions

The program shall take two integer arrays as input. Each array represents a non-negative number. Each...
The program shall take two integer arrays as input. Each array represents a non-negative number. Each element in the array is one digit however when all digits in the array are combined a number is formed. See example below: int Array1 = {4,5,6,7} represents number 7654 int Array2 = {2,3,4,5} represents number 5432 You will add the two numbers i.e., 7654 + 5432 = 13086 and store it in a new array similar to how the numbers were stored earlier...
Use a while(true) loop to ask the user to “Enter a non-negative integer (enter negative integer...
Use a while(true) loop to ask the user to “Enter a non-negative integer (enter negative integer to quit):” and store this into an int named n. If the user enters a negative int for n, the while loop is broken via the brake statement. Otherwise, in the remaining part of the while loop, use a for loop to compute the sum of the inverse factorials from 0 to n, that is sum = 1/0! + 1/1! + 1/2! + ....
Given a string and a non-negative int n, we'll say that the front of the string...
Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front; frontTimes("Chocolate", 2) → "ChoCho" frontTimes("Chocolate", 3) → "ChoChoCho" frontTimes("Abc", 3) → "AbcAbcAbc" Must work the following problem using a while loop or do while.
Write a program factor that prints the prime factors of a specified non-negative integer. The integer...
Write a program factor that prints the prime factors of a specified non-negative integer. The integer will be provided as a command-line argument. You may assume that the integer will be greater than 1 and less than or equal to the largest signed integer on your platform (that is, you may use an int).
Write a function decimalToBinary(n) that converts a positive decimal integer n to a string representing the...
Write a function decimalToBinary(n) that converts a positive decimal integer n to a string representing the corresponding binary number. Do the conversion by repeatedly dividing the number n by 2 using integer division, keepting track of the remainders, until the number is reduced to 0. The remainders written in reverse order form the binary number string. Do integer division of 5 by 2, so that N//2 is 2 with remainder 1. Now divide 2 by 2 to get 1 with...
Assignment Instructions: 1) The Factorial The factorial of a non-negative integer ??, denoted by ??!, is...
Assignment Instructions: 1) The Factorial The factorial of a non-negative integer ??, denoted by ??!, is the product of all positive integers less than or equal to ??. The textbook has an example of a recursive MIPS implementation of factorial. Additionally, a simplified version of the MIPS assembly language recursive implementation of the factorial function is attached. Trace the factorial example carefully using QTSPIM 2) Recursive definition of multiplication The function ??????????(??, ??) for two positive integers 1 ? ??,...
Assignment Instructions: 1) The Factorial The factorial of a non-negative integer ??, denoted by ??!, is...
Assignment Instructions: 1) The Factorial The factorial of a non-negative integer ??, denoted by ??!, is the product of all positive integers less than or equal to ??. The textbook has an example of a recursive MIPS implementation of factorial. Additionally, a simplified version of the MIPS assembly language recursive implementation of the factorial function is attached. Trace the factorial example carefully using QTSPIM 2) Recursive definition of multiplication The function ??????????(??, ??) for two positive integers 1 ? ??,...
8. Definition: A set A is finite if there exists a non-negative integer c such that...
8. Definition: A set A is finite if there exists a non-negative integer c such that there exists a bijection from A to {n ∈ N : n ≤ c}. (The integer c is called the cardinality of A.) (a) Let A be a finite set, and let B be a subset of A. Prove that B is finite. (Hint: induction on |A|. Note that our proof can’t use induction on |B|, or indeed refer to “the number of elements...
Create a CubesSum application that prompts the user for a non-negative integer and then displays the...
Create a CubesSum application that prompts the user for a non-negative integer and then displays the sum of the cubes of the digits.   b) Modify the application to determine what integers of two, three, and four digits are equal to the sum of the cubes of their digits.(Java Programming )
The factorial of a non-negative integer is defined as follows: n! = 1 × 2 ×...
The factorial of a non-negative integer is defined as follows: n! = 1 × 2 × ... × (n − 1) × n A. Write a function that takes an input value n and returns its factorial result n!. Ensure that your function returns an error statement if the input n is either a negative or a non-integer value. You cannot use the prod() or factorial() functions. The Euler number e is calculated as the sum of the infinite series...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT