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

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'

Related

Lua - Match pattern for CSV import to array, that factors in empty values (two commas next to each other)

I have been using the following Lua code for a while to do simply csv to array conversions, but everything previously had a value in every column, but this time on a csv formatted bank statement there are empty values, which this does not handle.
Here’s an example csv, with debit and credits.
Transaction Date,Transaction Type,Sort Code,Account Number,Transaction Description,Debit Amount,Credit Amount,Balance
05/04/2022,DD,'11-70-79,6033606,Refund,,10.00,159.57
05/04/2022,DEB,'11-70-79,6033606,Henry Ltd,30.00,,149.57
05/04/2022,SO,'11-70-79,6033606,NEIL PARKS,20.00,,179.57
01/04/2022,FPO,'11-70-79,6033606,MORTON GREEN,336.00,,199.57
01/04/2022,DD,'11-70-79,6033606,WORK SALARY,,100.00,435.57
01/04/2022,DD,'11-70-79,6033606,MERE BC,183.63,,535.57
01/04/2022,DD,'11-70-79,6033606,ABC LIFE,54.39,,719.20
I’ve tried different patterns (https://www.lua.org/pil/20.2.html), but none seem to work, I’m beginning to think I can’t fix this via the pattern as it’ll break how it works for the rest? I appreciate it if anyone can share how they would approach this…
local csvfilename = "/mnt/nas/Fireflyiii.csv"
local MATCH_PATTERN = "[^,]+"
local function create_array_from_file(csvfilename)
local file = assert(io.open(csvfilename, "r"))
local arr = {}
for line in file:lines() do
local row = {}
for match in string.gmatch(line, MATCH_PATTERN) do
table.insert(row, match)
end
table.insert(arr, row)
end
return arr
end

I get an error when Octave runs my Logarithm

i am trying to get my function to work.
The values for "time" and "value" are taken from a raw data txt file (time and value are raw data parsed by my programm).
Just for the purpose of demonstration i chose diffrent values for time and value.
I can also get other calculations to work, i just have a problem with getting my Log fn to work.
%Declaration (a time between 0-60s, a value between 0-200)
ti= (0.5);
q = (3);
L1 = 3/(log10(2));%9.9658
L2 = log10(2/3); %-0.17609
time = 40 %anything between 0 and 60
value = 90 %anything between 0 and 200
%f2 = Log Function
f2=figure(2);
y2= 9.9658*log10(1/(time*value*0.5*10*-0.17609));
x2=time;
fplot(x2,y2);
xlabel('Time in s'), ylabel('Value in db'),title('Calculations'),set(gca,'fontsize',15); grid on
The result i get is:
error: Question: operator *: nonconformant arguments (op1 is 38x1, op2 is 38x1)
error: called from
Question at line 11 column 5
if anyone had this error before i would be thankfull for help.
Best regards
The Answer to this question is as Cris Luengo pointed out in his answer to boot up a clean Octave session and change "fplot" to "plot".
plot(x2,y2); %works now
Big Thanks!

Function to convert a decimal into that of any base

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.

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)

random line in file

This question was given to me during an interview. The interview is long over, but I'm still thinking about hte problem and its bugging me:
You have a language that contains the following tools: a rand() function, while and for loops, if statements, and a readline() method (similar to python's readline()). Given these tools, write an algorithm that returns a random line in the file. You don't know the size of the file, and you can only loop over the file's contents once.
I don't know the desired answer, but my solution would be the following:
chosen_line = ""
lines = 0
while (current_line = readline()):
if (rand(0, lines) == 0):
chosen_line = current_line
lines++
return chosen_line
Edit: A good explanation why this works was posted in this comment.
One method, guaranteeing a uniform distribution:
(1) Read the file line-by-line into an array (or similar, e.g. python list)
(2) Use rand() to select a number between 0 and largest index in the array.
Another, not guaranteeing a uniform distribution:
Read each line. On each read, also call rand(). If over a threshold, return the line.
Although similar to Marcin's third option, Luc's implementation always returns the first line, while parsing the whole file.
It should be something like:
chosen_line = ""
treshold = 90
max = 100
while chosen_line == "":
current_line = readline()
if (rand(0, max) > treshold):
chosen_line = current_line
print chosen_line
You could also return current_line in the case no line was chosen and you read the whole file.