Giving Value to Python3 Count String - count

I am running a loop equation that divides or subtracts. Every time it divides I want it to represent each division with the # 2 and every time it subtracts I want it to represent the subtractions with a 1. I then want that count string to be a value that I can manipulate with some basic math. Basically it'll look like this: 20/2 = 10 (2) 10/2 = 5 (2) 5/2 = 2.5 (2) 2.5-.5 = 2 (1) 2/2 = 1 (2)
22212 <=== that I want to make a new value but with the way I have it coded, it's not working. I think it may have something to do with the end='' in the code.
I've tried giving the value of the string = to a int value and tried joining the string but no luck so far.
num = 20
while num >= 1.5:
num /= 2
v = 1
print(v, end='')
if int(num) != num:
num -= .5
v = 2
print(v, end='') #trying to make the output here a value
nv = ''.join(str(int(v)))
nv = int(v) #trying to give the joined strs of nv a value
print(nv) #trying to get this to print the combined valued of v to something that math can be applied to.
print('')
The code doesn't give any errors I just can't figure out how to make the output and actual number that I can manipulate.

you are printing v = 1 after your division. In your post you said you want a 2 for division, I am assuming what you wrote in the post is the result you want.
a = ""
num = 20
while num >= 1.5:
num /= 2
a += "2"
if int(num) != num:
num -= .5
a += "1"
print(a)
now a is a string with your desired result. You can always convert that String to an int to do some math with it.

Related

Is it possible to find a few common multiples of a list of numbers, without them having to be integers?

I don't even know if something like this is possible, but:
Let us say we have three numbers:
A = 6
B = 7.5
C = 24
I would like to find a few evenly spaced common multiples of these numbers between 0 and 2.
So the requirement is: one_of_these_numbers / common_multiple = an_integer (or almost an integer with a particular tolerance)
For example, a good result would be [0.1 , 0.5 , 1 , 1.5]
I have no idea if this is possible, because one can not iterate through a range of floats, but is there a smart way to do it?
I am using python, but a solution could be represented in any language of your preference.
Thank you for your help!
While I was writing my question, I actually came up with an idea for the solution.
To find common divisors using code, we have to work with integers.
My solution is to multiply all numbers by a factor = 1, 10, 100, ...
so that we can act as if they are integers, find their integer common divisors, and then redivide them by the factor to get a result.
Better explained in code:
a = 6
b = 7.5
c = 24
# Find a few possible divisors between 0 and 2 so that all numbers are divisible
by div.
# We define a function that finds all divisors in a range of numbers, supposing
all numbers are integers.
def find_common_divisors(numbers, range_start, range_end):
results = []
for i in range(range_start + 1, range_end + 1):
if all([e % i == 0 for e in numbers]):
results.append(i)
return results
def main():
nums = [a, b, c]
range_start = 0
range_end = 2
factor = 1
results = [1]
while factor < 11:
nums_i = [e * factor for e in nums]
range_end_i = range_end * factor
results += [e / factor for e in find_common_divisors(nums_i, range_start, range_end_i)]
factor *= 10
print(sorted(set(results)))
if __name__ == '__main__':
main()
For these particular numbers, I get the output:
[0.1, 0.3, 0.5, 1, 1.5]
If we need more results, we can adjust while factor < 11: to a higher number than 11 like 101.
I am curious to see if I made any mistake in my code.
Happy to hear some feedback.
Thank you!

Pascal's Triangle in SML

I'm trying to write a function of the type:
pascal : int * int -> int
where the pair of ints represent the row and column, respectively, of Pascal's triangle.
Here's my attempt:
fun pascal(i : int, j : int) : int =
if (i = 0 andalso j = 0) orelse i = j orelse i = 0
then 1
else
pascal(i - 1, j - 1) + pascal(i - 1, j);
It works for my base cases but gives me strange output otherwise. For instance:
pascal(4, 2) gives me 11 and pascal(4, 1) gives me 15
It's a bit strange because, as long as the if clause fails and the else gets evaluated, I do want to return the sum of the element one row above and the element one row above and one element to the left.
What am I doing wrong?
Consider pascal 1 0. If you're using zero-based indexing for the table then this should be equal to 1. But:
pascal 1 0 = pascal 0 -1 + pascal 0 0 = 2
You should put some guards to deal with negative indices and indices where j is greater than i.

Calculate if trend is up, down or stable

I'm writing a VBScript that sends out a weekly email with client activity. Here is some sample data:
a b c d e f g
2,780 2,667 2,785 1,031 646 2,340 2,410
Since this is email, I don't want a chart with a trend line. I just need a simple function that returns "up", "down" or "stable" (though I doubt it will ever be perfectly stable).
I'm terrible with math so I don't even know where to begin. I've looked at a few other questions for Python or Excel but there's just not enough similarity, or I don't have the knowledge, to apply it to VBS.
My goal would be something as simple as this:
a b c d e f g trend
2,780 2,667 2,785 1,031 646 2,340 2,410 ↘
If there is some delta or percentage or other measurement I could display that would be helpful. I would also probably want to ignore outliers. For instance, the 646 above. Some of our clients are not open on the weekend.
First of all, your data is listed as
a b c d e f g
2,780 2,667 2,785 1,031 646 2,340 2,410
To get a trend line you need to assign a numerical values to the variables a, b, c, ...
To assign numerical values to it, you need to have little bit more info how data are taken. Suppose you took data a on 1st January, you can assign it any value like 0 or 1. Then you took data b ten days later, then you can assign value 10 or 11 to it. Then you took data c thirty days later, then you can assign value 30 or 31 to it. The numerical values of a, b, c, ... must be proportional to the time interval of the data taken to get the more accurate value of the trend line.
If they are taken in regular interval (which is most likely your case), lets say every 7 days, then you can assign it in regular intervals a, b, c, ... ~ 1, 2, 3, ... Beginning point is entirely your choice choose something that makes it very easy. It does not matter on your final calculation.
Then you need to calculate the slope of the linear regression which you can find on this url from which you need to calculate the value of b with the following table.
On first column from row 2 to row 8, I have my values of a,b,c,... which I put 1,2,3, ...
On second column, I have my data.
On third column, I multiplied each cell in first column to corresponding cell in second column.
On fourth column, I squared the value of cell of first column.
On row 10, I added up the values of the above columns.
Finally use the values of row 10.
total_number_of_data*C[10] - A[10]*B[10]
b = -------------------------------------------
total_number_of_data*D[10]-square_of(A[10])
the sign of b determines what you are looking for. If it's positive, then it's up, if it's negative, then it's down, and if it's zero then stable.
This was a huge help! Here it is as a function in python
def trend_value(nums: list):
summed_nums = sum(nums)
multiplied_data = 0
summed_index = 0
squared_index = 0
for index, num in enumerate(nums):
index += 1
multiplied_data += index * num
summed_index += index
squared_index += index**2
numerator = (len(nums) * multiplied_data) - (summed_nums * summed_index)
denominator = (len(nums) * squared_index) - summed_index**2
if denominator != 0:
return numerator/denominator
else:
return 0
val = trend_value([2781, 2667, 2785, 1031, 646, 2340, 2410])
print(val) # -139.5
in python:
def get_trend(numbers):
rows = []
total_numbers = len(numbers)
currentValueNumber = 1
n = 0
while n < len(numbers):
rows.append({'row': currentValueNumber, 'number': numbers[n]})
currentValueNumber += 1
n += 1
sumLines = 0
sumNumbers = 0
sumMix = 0
squareOfs = 0
for k in rows:
sumLines += k['row']
sumNumbers += k['number']
sumMix += k['row']*k['number']
squareOfs += k['row'] ** 2
a = (total_numbers * sumMix) - (sumLines * sumNumbers)
b = (total_numbers * squareOfs) - (sumLines ** 2)
c = a/b
return c
trendValue = get_trend([2781,2667,2785,1031,646,2340,2410])
print(trendValue) # output: -139.5

recursive function to convert string to integer ML

I need to write my own recursive function in ML that somehow uses ord to convert a string of numbers to integer type. I can use helper functions, but apparently I should be able to do this without using one (according to my professor).
I can assume that the input is valid, and is a positive integer (in string type of course).
So, the call str2int ("1234") should output 1234: int
I assume I will need to use explode and implode at some point since ord operates on characters, and my input is a string. Any direction would be greatly appreciated.
Given that you asked, I guess I can ruin all the fun for you. This will solve your problem, but ironically, it won't help you.
Well, the ordinal number for the character #'0' is 48. So, this means that if you subtract of any ordinal representing a digit the number 48 you get its decimal value. For instance
ord(#"9") - 48
Yields 9.
So, a function that takes a given character representing a number from 0-9 and turns it into the corresponding decimal is:
fun charToInt(c) = ord(c) - 48
Supposing you had a string of numbers like "2014". Then you can first explode the string into list of characters and then map every character to its corresponding decimal.
For instance
val num = "2014"
val digits = map charToInt (explode num)
The explode function is a helper function that takes a string and turn it into a list of characters.
And now digits would be a list of integers representing the decimal numbers [2,0,1,4];
Then, all you need is to apply powers of 10 to obtain the final integer.
2 * 10 ^ 3 = 2000
0 * 10 ^ 2 = 0
1 * 10 ^ 1 = 10
4 * 10 ^ 0 = 4
The result would be 2000 + 0 + 10 + 4 = 2014
You could define a helper function charsToInt that processes the digits in the string from left to right.
At each step it converts the leftmost digit c into a number and does addition with the 10x-multiple of n (which is the intermediary sum of all previously parsed digits) ...
fun charsToInt ([], n) = n
| charsToInt (c :: cs, n) = charsToInt (cs, 10*n + ord c - 48)
val n = charsToInt (explode "1024", 0)
Gives you: val n = 1024 : int
As you see the trick is to pass the intermediary result down to the next step at each recursive call. This is a very common technique when dealing with these kind of problems.
Here's what I came up with:
fun pow10 n =
if n = 0 then 1 else 10*pow10(n-1);
fun str2help (L,n) =
if null L then 0
else (ord(hd L)-48) * pow10(n) + str2help(tl L, n-1);
fun str2int (string) =
str2help(explode string, size string -1);
str2int ("1234");
This gives me the correct result, though is clearly not the easiest way to get there.

Python Programming While Loop

Hi I'm new to python and programming in general. I am trying write a program that uses a while loop to add integers from 1 to the number entered. the program also has to give an error statement if the user enters a 0 or negative number. So far the integers add up and the error statement works but the program is not looping, it only asks the user to input a number one time. Please help. This is my source code so far. Thanks
x = int(input("Enter a positive number not including zero:" ))
total = 0
n = 1
while n <= x:
total = total + n
n = n + 1
# prints the total of integers up to number entered
print("Sum of integers from 1 to number entered= ",total)
if x <= 0 or x == -x:
print ("invalid entry")
Try this code...
op='y'
while op=='y':
x = int(input("Enter a positive number not including zero:" ))
total = 0
n = 1
if x > 0:
while n <= x:
total = total + n
n = n + 1
# prints the total of integers up to number entered
print("Sum of integers from 1 to number entered= ",total)
else:
print ("invalid entry")
op = raw_input("Are you want to continue this operation (y/n):" )
Put your whole code this way
done = False
while not done:
//your entire code here except the last 2 lines
if x > 0:
done = True

Resources