Function to convert a decimal into that of any base - binary

I am doing this question via an Online learning platform, and there are test cases assigned which i must pass. The topic is Higher Order Functions.
Here is the question:
Write a function make_decimal_to_n_ary_converter that accepts a number n where 1 < n < 17, and returns a number converter that converts a given decimal number into that of base n.
Below is my code(I am supposed to use an inner function i.e converter(x))
def make_decimal_to_n_ary_converter(n):
def converter(x):
if x==0 or x==1:
return x
i=x
b=('A','B','C','D','E','F')
result = ""
while i>0:
a=i%n #3
if a<10:
result = str(i%n)+result
else:
d=a-10
result = b[d] + result
i=i//n
return result
return converter
#Lines below are not to be changed, part of qn
decimal_to_binary = make_decimal_to_n_ary_converter(2)
decimal_to_octal = make_decimal_to_n_ary_converter(8)
decimal_to_hexadecimal = make_decimal_to_n_ary_converter(16)
Here are some test cases that my code passes:
decimal_to_binary(213)
11010101
decimal_to_octal(213)
325
decimal_to_hexadecimal(213)
D5
make_decimal_to_n_ary_converter(15)(213)
E3
However, my code fails some private test cases, and feedback that i received was that my logic in the while loop is wrong. However, after printing some numbers, i failed to see anything wrong.
Would appreciate any help, thank you!

Solved it. My mistake was that for base cases x , i had to return a string instead.

Related

Need help rounding Mysql results that are returned from a python function

I am relatively new to python and I am working on creating a program in my fun time to automatically generate a sales sheet. It has several functions that pull the necessary data from a database, and reportlab and a few other tools to place the results onto the generated pdf. I am trying to round the results coming from the Mysql server. However, I have hit a point where I am stuck and all the ways I have tried to round the results throw an error code and do not work. I need a few examples to look at so I can see how this would work and any relevant feedback that would help me learn.
I have tried to use the mysql round function to round the results but that failed. I have also tried to round the results as part of the function that generates the unit cost itself. However, that has failed as well.
A large amount of the code has been deleted due to the security hole it would generate. Code provided is to show what I have done so far. Print result line is to verify that the code is working during development. It is not throwing any erroneous results and will be removed during the last stage of the project.
def upcpsfunc(self, upc):
mycursor = self.mydb.cursor()
command = "Select Packsize from name"" where UPC = %(Upc)s"
mycursor.execute(command, {'Upc': upc})
result = mycursor.fetchone()
print(result[0])
return result[0]
def unitcost(self,upc):
#function to generate unit cost
mycursor = self.mydb.cursor()
command = "Select Concat((Cost - Allow)/Packsize) as total from name
where UPC = %(Upc)s"
mycursor.execute(command, {'Upc': upc})
result = mycursor.fetchone()
print (result[0])
return result[0]
As for the expected results, I would prefer the mysql command round the results before it sends it to Reportlab for placement. So far the results are 4 or 5 digits, which is not ideal. I want the results to have two decimal places, since it would be money. The desired output is 7.50 instead 7.5025
The round function can be used to round numbers:
>>> round(7.5025, 2)
7.5
To get the extra 0 on the end, you can use the following code:
>>> def round_money(n):
s = str(round(n, 2))
if len(s) == 1: # exact dollar
return s + ".00"
elif len(s) == 3: # exact x10 cents
return s + "0"
return s
>>> round_money(6)
'6.00'
>>> round_money(7.5025)
'7.50'
Note that this function returns a string, because 7.50 cannot be represented by an integer in python.
Just as an alternative way to the one already provided, you can do the same thing with string formatting (it'll truncate the decimals though, so you can still round beforehand):
>>> '{:,.2f}'.format(0)
'0.00'
>>> '{:,.2f}'.format(15342.62412)
'15,342.62'

Writing an exception function

I am currently learning on an online learning platform, and my code has to pass the test cases(included below)
Heres the question:
Write a higher-order function exception_function which will return a function with exceptions. exception_function should take in a function f(x), an integer input, and an integer output, and return another function g(x). The output of g(x) should be the same as f(x), except that when x is the same as the integer input, the output will be returned.
For example, given that we have a function sqrt which returns the square root of the argument. Using new_sqrt = exception_function(sqrt, 7, 2) we obtain new_sqrt, which behaves similarly to sqrt except for new_sqrt(7), where the value of 2 will be returned.
Below is the answer template
from math import *
def exception_function(f, rejected_input, new_output):
"""Your code here"""
pass
#################
#DO NOT REMOVE#
#################
new_sqrt = exception_function(sqrt, 7, 2)
Test Cases:
new_sqrt(9) -expected answer 3
new_sqrt(7) -expected answer 2
Here is what im not sure about.
How to control what f will return without changing f itself?
Thank you very much for your time.
Managed to solve it!
def exception_function(f, rejected_input, new_output):
def inner_function(x):
if x==rejected_input:
return new_output
else:
return f(x)
return inner_function
new_sqrt = exception_function(sqrt, 7, 2)

defining a function (somehow wrong syntax)

I wanna create a program that multiplies the users age by 50. I defined a function that allows you to do that but it still says that the "def" has the wrong syntax . please tell me what im doing wrong . thnks ( and yes im a beginner)
age = print(int(input("gimme age"))
def by_50(x):
return x * 50
print(by_50(age))
The problem is that you're missing a finishing bracket in print(int(input("gimme age")).
In addition, with age = print(int(input("gimme age"))) you are trying to assign the return value of the function print() to age, but print() always returns None, which isn't very uesful.
Instead, you should be assigning the return value of input(): age = int(input("gimme age")).
Full program:
age = int(input("gimme age"))
def by_50(x):
return x * 50
print(by_50(age))

How "return" works in Python 2.7 user defined function

The use of the command "return" has always been bothering me since I started learning Python about a month ago(completely no programming background)
The function "double()" seems working fine without me have to reassign the value of the list used as an argument for the function and the value of the elements processed by the function would double as planned. Without the need to assign it outside the function.
However, the function "only_upper()" would require me to assign the list passed as argument through the function in order to see the effect of the function. I have to specify t=only_upper(t) outside of the function to see the effect.
So my question is this: Why are these two seemingly same function produces different result from the use of return?
Please explain in terms as plain as possible due to my inadequate programming skill. Thank you for your input.
def double(x):
for i in range(len(x)):
x[i] = int(x[i])*2
return x
x = [1, 2, 3]
print double(x)
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
t = res
return t
t = ['a', 'B', 'C']
t = only_upper(t)
print t
i am assuming that this is your first programming language hence the problem with understanding the return statement found in the functions.
The return in our functions is a means for us to literally return the values we want from that given 'formula' AKA function. For example,
def calculate(x,y):
multiply = x * y
return multiply
print calculate(5,5)
the function calculate defines the steps to be executed in a chunk. Then you ask yourself what values do you want to get from that chunk of steps. In my example, my function is to calculate the multiplied value from 2 values, hence returning the multiplied value. This can be shorten to the following
def calculate(x,y):
return x * y
print calculate(5,5)

Python 2.7.5, using a loop within a function and calling the function

I can't seem to get user input for a number of times to display. For example, if the input is
Jeff 6
The output should be
Jeff
Jeff
Jeff
Jeff
Jeff
Jeff
I'm new to functions in Python, but here is my code thus far:
def getName():
name = raw_input("please enter name")
return name
def getRepval():
irepnum = float(raw_input("please enter number to show name entered"))
return irepnum
def inamed(name, irepnum):
count = 1 #the loop to show the name entered by the user
while irepnum != count:
print name
count += 1 #do I need to use return??
def main(): #having the main func like this gives me an infinite loop
irepnum = 0
iname = getName() #I think my problem is somewhere here.
irepnum = getRepval()
inamed(irepnum,name)
main()
You need to call inamed(iname, irepnum), not inamed(irepnum, name), as you are doing now.
Other than the obvious mistake of name not being defined (the actual variable is called iname), the wrong order causes irepnum in the function to be set to a string the user entered as name. Since count, no matter how large, never compares equal to the passed string, the code loops infinitely.
Several tips:
Learn to use the for loop and xrange. The idiom you want is for count in xrange(irepnum):. (Using it would have prevented this bug.)
Give more distinctive names to your identifiers. Currently you have an inamed function and an iname variable. Confusing.
Don't use floats where an int would suffice. Misusing floats is asking for trouble.