Question

In: Computer Science

def num_to_digit_rec(num, base): """ Return a list of digits for num with given base; Return an...

def num_to_digit_rec(num, base):
  """
  Return a list of digits for num with given base;
  Return an empty list [] if base < 2 or num <= 0
  """
  # Write your code here
  return []

def digit_sum(num, base):
  """
  Return the sum of all digits for a num with given base
  Your implementation should use num_to_digit_rec() function
  """
  # Write your code here
  return 0 

def digit_str(num, base):
  """
  Given a number and a base, for base between [2, 36] inclusive
  Converts the number to its string representation using digits
  0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
  to represent digits 0 to 35.
  Return the string representation of the number
  Return an empty string '' if base is not between [2, 36]
  Your implementation should use num_to_digit_rec() function
  """
  digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  # Can not find str representations for base not in [2, 36]
  if base > 36 or base < 2:
    return ""
  # Calculate and return the str representation for num for the given base
  # Write your code here
  return "" 

def uses_only(word, letters):
  """
  Return True if word only uses characters from letters;
  otherwise return False
  """
  # Write your code here
  return True

def digit_to_num(rep, base):
  """
  Return -1 if base is not between [2,36] inclusive;
  or if the string rep contains characters not a digit for the base;
  Return the number represented by the string for the given base otherwise.
  For example digit_to_num("1001", 2) is 9; digit_to_num("ABC", 16) is 2748. 
  """
  # Check if the base is valid
  if base > 36 or base < 2:
    return -1 
  digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  rep = rep.upper()
  # Check if the rep only uses proper digits
  # Write your code here
  return 0 

def run():
  num = int(input("Enter a num: "))
  base = int(input("Enter a base: "))
  print(f"Digit list is {num_to_digit_rec(num, base)}")
  print(f"Digit sum is {digit_sum(num, base)}")
  print(f"String Rep is {digit_str(num, base)}")
  rep = input(f"Enter a string rep of a num with base {base}: ")
  print(f"The number is {digit_to_num(rep, base)}")

if __name__ == "__main__":
  run()
  • num_to_digit_rec(num, base): Given a num and its base, convert the num to a list of digits in its base representation. 0 is converted to an empty list. You must implement this function using recursion. Do not use any loops/iterations.
  • digit_sum(num, base), Given a num and its base, find out sum of all of its digits in its base representation. You should use the num_to_digit_rec() function's result which is a list of all the digits. This function is an easy one-liner.
  • digit_str(num, base): Given a num and its base, convert the num to a string representation for that base, using Capital Letters A-Z to represent digit 10-35. This function only works for base between [2, 36]. Do make sure that 0 is converted to "0" for a valid base.
  • uses_only(word, letters): The same function in Chapter 9. It is a helper function needed to check a string representation's validity for the digit_to_num() function.
  • digit_to_num(rep, base): Given a string representation rep and its base, convert the string representation with a base to a number. For example digit_to_num("1001", 2) = 9, digit_to_num("z", 36) = 35. You may use uses_only() function to check that the string representation only uses valid digits for the given base.

Example:

Enter a num: 0
Enter a base: 5
Digit list is []
Digit sum is 0
String Rep is 0
Enter a string rep of a num with base 5: 3
The number is 3

Solutions

Expert Solution

Short Summary:

  • Provided the source code and sample output as per the requirements.

**************Please upvote the answer and appreciate our time.************

Source Code:

def num_to_digit_rec(num, base):
"""
Return a list of digits for num with given base;
Return an empty list [] if base < 2 or num <= 0
"""
# Write your code here
if base < 2 or num <= 0:
return []
  
if num == 0:
return num_to_digit_rec(num//base, base) + [num%base]

def digit_sum(num, base):
"""
Return the sum of all digits for a num with given base
Your implementation should use num_to_digit_rec() function
"""
numList = num_to_digit_rec(num,base)
total =0
for ele in range(0, len(numList)):
total = total + numList[ele]
# Write your code here
return total

def digit_str(num, base):
"""
Given a number and a base, for base between [2, 36] inclusive
Converts the number to its string representation using digits
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
to represent digits 0 to 35.
Return the string representation of the number
Return an empty string '' if base is not between [2, 36]
Your implementation should use num_to_digit_rec() function
"""
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# Can not find str representations for base not in [2, 36]
if base > 36 or base < 2:
return ""
# Calculate and return the str representation for num for the given base
# Write your code here
if num < base:
return digits[num]
else:
return digit_str(num//base,base) + digits[num%base]

def uses_only(word, letters):
"""
Return True if word only uses characters from letters;
otherwise return False
"""
# Write your code here
for character in word:
if character == letters:
return True
else:
return False

def digit_to_num(rep, base):
"""
Return -1 if base is not between [2,36] inclusive;
or if the string rep contains characters not a digit for the base;
Return the number represented by the string for the given base otherwise.
For example digit_to_num("1001", 2) is 9; digit_to_num("ABC", 16) is 2748.
"""
# Check if the base is valid
if base > 36 or base < 2:
return -1
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
rep = rep.upper()
# Check if the rep only uses proper digits
# Write your code here
if not uses_only(rep,digits):
return (int(rep,base))
  
return 0

def run():
num = int(input("Enter a num: "))
base = int(input("Enter a base: "))
print(f"Digit list is {num_to_digit_rec(num, base)}")
print(f"Digit sum is {digit_sum(num, base)}")
print(f"String Rep is {digit_str(num, base)}")
rep = input(f"Enter a string rep of a num with base {base}: ")
print(f"The number is {digit_to_num(rep, base)}")

if __name__ == "__main__":
run()

Refer the following screenshots for code indentation:

Sample Run:

**************************************************************************************

Feel free to rate the answer and comment your questions, if you have any.

Please upvote the answer and appreciate our time.

Happy Studying!!!

**************************************************************************************


Related Solutions

Python ONLY ONE STATEMENT ALLOWED PER FUNCTION (ONE RETURN STATEMENT ALLOWED) def plsfollowrule(num): return num like...
Python ONLY ONE STATEMENT ALLOWED PER FUNCTION (ONE RETURN STATEMENT ALLOWED) def plsfollowrule(num): return num like this. 1) create a function popular. The dictionary called database contains each people's hobby and their excitement level. This function searches the dictionary and returns a list of that most popular hobby to least popular hobby. If multiple hobbies have the same number of popularity, follow alphabetical order. #What is popular means? The dictionary contains each people's hobby. The programmer should search the dictionary...
Exercise: Write a program named factorial.py that contains the following two functions: def while_factorial(num) def for_factorial(num)...
Exercise: Write a program named factorial.py that contains the following two functions: def while_factorial(num) def for_factorial(num) These should calculate the factorial of a given number represented by the argument num using a while loop and a for loop respectively.
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return...
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return the length of the longest chain of 1's that start from the beginning. You MUST use a while loop for this! We will check. >>> longest_chain([1, 1, 0]) 2 >>> longest_chain([0, 1, 1]) 0 >>> longest_chain([1, 0, 1]) 1 """ i = 0 a = [] while i < len(submatrix) and submatrix[i] != 0: a.append(submatrix[i]) i += 1 return sum(a) def largest_rectangle_at_position(matrix: List[List[int]], x:...
def warmer_year(temps_then: List[int], temps_now: List[int]) -> List[str]: """Return a list of strings representing whether this year's...
def warmer_year(temps_then: List[int], temps_now: List[int]) -> List[str]: """Return a list of strings representing whether this year's temperatures from temps_now are warmer than past temperatures in temps_then. The resulting list should contain "Warmer" at the indexes where this year's temperature is warmer, and "Not Warmer" at the indexes where the past year was warmer, or there is a tie. Precondition: len(temps_then) == len(temps_now) >>> warmer_year([10], [11]) ['Warmer'] >>> warmer_year([26, 27, 27, 28], [25, 28, 27, 30]) ['Not Warmer', 'Warmer', 'Not Warmer',...
def hiCount(iterable): rtnVal = 0 most = '' for item in iterable: num = iterable.count(item) if...
def hiCount(iterable): rtnVal = 0 most = '' for item in iterable: num = iterable.count(item) if num > rtnVal: most = item rtnVal = num return tuple(most, rtnVal) lyric = "you don't own me" print(hiCount(lyric)) does all the for then the return Python
(True or False) The following function will compile. void print(int num) { return num+1; } Group...
(True or False) The following function will compile. void print(int num) { return num+1; } Group of answer choices True False Flag this Question Question 2 10 pts (True or False) The following code will output "I was true". bool isGreater(string s1, string s2) { if(s1 > s2) { return true; } return false; } int main() { if(isGreater("before","back")) { cout << "I was true"; } else { cout << "I was false"; } return 0; } Group of answer...
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value...
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value pairs of the dictionary as tuples (key, value), reverse sorted by value (highest first) and where multiple keys with the same value appear alphabetically (lowest first).
Q1: Given the following code, what is returned by tq(4)? int tq(int num){ if (num ==...
Q1: Given the following code, what is returned by tq(4)? int tq(int num){ if (num == 0) return 0; else if (num > 100) return -1; else     return num + tq( num – 1 ); } Group of answer choices: 0 4 -1 10 Q2: Given that values is of type LLNode<Integer> and references a linked list (non-empty) of Integer objects, what does the following code do if invoked as mystery(values)? int mystery(LLNode<Integer> list) {    if (list.getLink() ==...
In Python, Given a list of numbers, return a list where all adjacent == elements have...
In Python, Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1,2,2,3,3,2,2,4] returns [1,2,3,2,4]. You may create a new list or modify the passed in list (set function does not work in this case).
#Write a program in Python that given a list of positive integers, return another list where...
#Write a program in Python that given a list of positive integers, return another list where each element corresponds to the sum of the digits of the elements o#f the given list. #Example: # input # alist=[124, 5, 914, 21, 3421] # output # sum=[7, 5, 14, 3, 18]
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT