For loop not working stating the endpoint is a float - python

So for context, I'm working on a program that requires the Guass formula. It's used to find for example, 5 + 4 + 3 + 2 + 1, or, 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1.
The formula is (n*(n + 1))/2,
I tried to incorporate this into a for loop, but I'm getting an error stating:
"'float' object cannot be interpreted as an integer"
This is my code:
# Defining Variables #
print("Give me a start")
x = int(input())
print("Give me a delta")
y = int(input())
print("Give me an amount of rows")
z = int(input())
archive_list = []
f = z + 1
stop = z*f
final_stop = stop/2
# Main Logic #
for loop in range(1,final_stop,1):
print("hi")
I would appreciate a response on why it wasn't working as well as a fixed code.
Thanks in advance!

As #ForceBru noted in his excellent comment, the problem is that the endpoint final_stop is a float, instead of an int.
The reason is because when computing it you used a single / instead of double.
If you replace
final_stop = stop/2
with
final_stop = stop//2,
then it should work fine.

Related

evaluation of polynomials of order 15 gives unexpected results (OpenCV Coordinates Output Python)

I've created a formula with polynomial regression to calculate a drag point from an input. I tested the formula in a separate file with the input, and the output appears to be working as intended. However, in the actual file, it seems to be outputting tremendously incorrect numbers. My first thought was that the output style for OpenCV was in some odd format for the numbers, but when I printed the values they were just fine. It appears to work just fine with smaller formulas, but gives wild values for my created formula. Any help would be appreciated. Below are the formulae for calculating the x and y with a test input and a correct output, vs what I'm getting in the actual file. Thanks.
def triang_x(x1):
x2 = (-6.8808613455609384e+005) + (3.2312735687925651e+003 * x1)
+ (-6.0019455279289815e+000 * x1**2) + (1.0786025430222985e-002 * x1**3)
+ (-2.8031333306353576e-005 * x1**4) + (4.7125204049478773e-008 * x1**5)
+ (-3.8733353649642116e-011 * x1**6) + (1.4733899082497896e-014 * x1**7)
+ (-5.1033986030610612e-018 * x1**8) + (2.7445807881521161e-021 * x1**9)
+ (1.4039325861603808e-024 * x1**10) + (-7.8303365296494140e-027 * x1**11)
+ (2.0700235162417034e-029 * x1**12) + (-2.5633522287710555e-032 * x1**13)
+ (1.4236656075804622e-035 * x1**14) + (-2.9388878284829885e-039 * x1**15)
return x2
def triang_y(y1):
y2 = ((2.9536073194970668e+004) + (-7.2584981060026985e+002 * y1)
+ (5.9991721893954519e+000 * y1**2) + (-1.4273839368311947e-002 * y1**3)
+ (-6.1205911580247642e-005 * y1**4) + (4.1603526512587676e-007 * y1**5)
+ (-6.9546008738218303e-010 * y1**6) + (-1.1072665851528698e-013 * y1**7)
+ (-6.4446469064614884e-016 * y1**8) + (8.0190196135612936e-018 * y1**9)
+ (-8.8768139841444641e-021 * y1**10) + (-1.3685149110264805e-023 * y1**11)
+ (1.3193560897991867e-026 * y1**12) + (5.4138560249698032e-029 * y1**13)
+ (-9.5141032455036651e-032 * y1**14) + (4.4497796299711634e-035 * y1**15))
return y2
# Test Values are x:1116 y:398
#Correct Output is x:900.892612375319 y:889.0486684303542
#Output received in main is 10415680.385044796 -167144.0485716732
The way your question is posed currently, I can't make heads or tails of it.
I can tell you that your first function has an error: you're trying to assign a sum of 16 summands but when you break that line, everything following will not be part of that sum. You should have gotten an IndentationError... Unless the code in your question is indented differently from what you actually ran on your own computer. If you indented that just right, you would simply have a bunch of 2-summand additions going off into nowhere because it's perfectly legal in python to have an expression whose value you don't assign to anything. To fix that, put parentheses ( and ) around the entire expression on the right-hand side of the assignment.
Your second function looks okay and appears to work as you want it. I can't reproduce the "wrong values" you state in your question.
Beyond that... instead of writing such a huge python expression, simply use numpy to express the coefficients and the evaluation of the polynomial:
import numpy as np
coeffs_x = np.float64([
-6.8808613455609384e+005, # 0
+3.2312735687925651e+003, # 1
-6.0019455279289815e+000, # 2
+1.0786025430222985e-002, # 3
-2.8031333306353576e-005, # 4
+4.7125204049478773e-008, # 5
-3.8733353649642116e-011, # 6
+1.4733899082497896e-014, # 7
-5.1033986030610612e-018, # 8
+2.7445807881521161e-021, # 9
+1.4039325861603808e-024, # 10
-7.8303365296494140e-027, # 11
+2.0700235162417034e-029, # 12
-2.5633522287710555e-032, # 13
+1.4236656075804622e-035, # 14
-2.9388878284829885e-039, # 15
])
triang_x = np.polynomial.Polynomial(coeffs_x)
coeffs_y = np.float64([
+2.9536073194970668e+004, # 0
-7.2584981060026985e+002, # 1
+5.9991721893954519e+000, # 2
-1.4273839368311947e-002, # 3
-6.1205911580247642e-005, # 4
+4.1603526512587676e-007, # 5
-6.9546008738218303e-010, # 6
-1.1072665851528698e-013, # 7
-6.4446469064614884e-016, # 8
+8.0190196135612936e-018, # 9
-8.8768139841444641e-021, # 10
-1.3685149110264805e-023, # 11
+1.3193560897991867e-026, # 12
+5.4138560249698032e-029, # 13
-9.5141032455036651e-032, # 14
+4.4497796299711634e-035, # 15
])
triang_y = np.polynomial.Polynomial(coeffs_y)
print(triang_x(1116), triang_y(398))
# => 900.8926123741549 889.0486684304415

recursive function multiply and sum

Hope to find some help here with a new excercise.
I luckily understand how to use recursive functions, but this one is killing me, im probably just thinking too much outside of the box.
We're given a string:
c = "3+4*5+6+1*3"
And now we have to code a function, which recursivly gives us the result of that calculation.
Now i know the recursive end should be the length of the string, which should be 1.
Our professor did give us another example which we should use for this function.
int(number)
string.split(symbol, 1)
we have following code given:
c = "3+4*5+6+1*3"
print(c)
print()
sub1, sub2 = c.split("+", 1)
print("Result with '+':")
print("sub1=" + sub1)
print("sub2=" + sub2)
print()
sub1, sub2 = c.split("*", 1)
print("Result with '*':")
print("sub1=" + sub1)
print("sub2=" + sub2)
print()
My thoughts were to split the strings to a minimum, so i can turn them into integers and than sum them together. But im absolutly lost there how the code should look like, im a real beginner so im really sorry. I dont even know it the beginning i was thinking of is right. Still hoping, someone can help!
what i had:
def calc(string):
if len(string) == 1:
return string
Thanks for all of you!
Greets
Chrissi
I created a function that solves equations like these. However, the only characters possible are numbers, and operators add (+) and mult (*). If you try to use any other characters such as spaces, there's going to be errors.
# Solves a mathematical equation containing digits [0-9], and operators
# such as add + or multiply *
def solve(equation, operators, oindex=0):
# If an operator is available, use the operator
if (oindex < len(operators)):
# Get the current operator and pair: a op b
op = operators[oindex]
pair = equation.split(op, 1)
# If the pair is a pair (has 2 elements)
if (len(pair) == 2):
# Solve left side
a = solve(pair[0], operators)
# Solve right side
b = solve(pair[1], operators)
# If current operator is multiply: multiply a and b
if (op == '*'):
print(a, '*', b, '=', a*b)
return a * b
# If current operator is add: add a and b
elif (op == '+'):
print(a, '+', b, '=', a+b)
return a + b
# If it's not a pair, try using another operator
else:
return solve(equation, operators, oindex+1)
else:
# If no operators are available, then equation is
# just a number.
return int(equation)
if __name__ == '__main__':
equation = "3+4*5+6+1*3"
# If mult (*) takes precedence, operator order is "+*"
# > 3+4*5+6+1*3 = ((3)+((4*5)+((6)+(1*3))))
# = ((3)+((20)+((6)+(3))))
# = ((3)+(20+(9)))
# = ((3)+(29))
# = (32)
print("MULT, then ADD -> ",equation + " = ", solve(equation, "+*"))
# If add (+) takes precedence, operator order is "*+"
# > 3+4*5+6+1*3 = ((3+4)*(((5)+(6+1))*(3)))
# = ((7)*((5+7)*(3)))
# = ((7)*(12*3))
# = (7*36)
# = (252)
print("ADD, then MULT -> ",equation + " = ", solve(equation, "*+"))
To set the operators, you can use the paramter operators, which is a string that takes all supported operators. In this case: +*.
The order of these characters matter, changing the precedence of each operator inside the equation.
Here's the output:
4 * 5 = 20
1 * 3 = 3
6 + 3 = 9
20 + 9 = 29
3 + 29 = 32
MULT, then ADD -> 3+4*5+6+1*3 = 32
3 + 4 = 7
6 + 1 = 7
5 + 7 = 12
12 * 3 = 36
7 * 36 = 252
ADD, then MULT -> 3+4*5+6+1*3 = 252

Need information on Basic Python Arthematic operation

I am using Python Version 3.6.4
I was trying to write a basic python code in Jupyter Notebook where I found my code acting funny.
The below given code is working as expected But when I change the operation to (+) in the 4th line of code print( x, '+', y, '=', x+y) then it is resulting with Error.
Question is why is this unexpected behavior happening when there is a change of operator where multiplication works fine and addition results with error?
def fuc(x):
x = input('Enter the number:')
for y in range(1,11):
print( x, 'x', y, '=', x*y)
print(fuc(2))
The user input (i.e. x) is string. y is integer. Multiplication between string and integer is valid python operation. Addition between integer and string is not. Note that I doubt your code with multiplication works as expected, i.e. it will not multiply the number, but repeat the string, e.g.
>>> '3' * 4
'3333'
To deal with the problem you need to convert the user input to int:
x = int(input('Enter the number:'))
Note that this will not handle any invalid input, e.g. not numeric input and will raise an exception.
EDIT: Include example code snippet:
def fuc(x):
x = int(input('Enter the number:'))
for y in range(1,11):
print(x, '+', y, '=', x+y)
# print(f'{x} + {y} = {x+y}') # in 3.6+ you better use this
fuc(2)
output in python3
Enter the number:3
3 + 1 = 4
3 + 2 = 5
3 + 3 = 6
3 + 4 = 7
3 + 5 = 8
3 + 6 = 9
3 + 7 = 10
3 + 8 = 11
3 + 9 = 12
3 + 10 = 13
>>>
Normally I would use string formatting for the print, but in this case I keep as in the original code
you can try this piece of code:
def fuc(x):
x = float(input('please enter your desired number'))
for i in range(1,11):#generally i is used as an iterable
print( "{}*{} '=' ",x*i)
print(fuc())

Round to whole numbers without using conditional statements in Python - Logic

I'm taking a Python course at Udacity, and I'm trying to work this out for myself without looking at the answer. Perhaps you can give me a hint for my logic?
Below are the instructions and what I have so far. We haven't learned conditional statements yet, so I can't use those. We've only learned how to assign/print a variable, strings, indexing strings, sub-sequences, and .find. They just introduced the str command in this final exercise.
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.
# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'
# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.
# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)
x = 3.54159
#ENTER CODE BELOW HERE
x = str(x)
dec = x.find('.')
tenth = dec + 1
print x[0:dec]
////
So this gets me to print the characters up to the decimal point, but I can't figure out how to have the computer check whether "tenth" is > 4 or < 5 and print out something according to the answer.
I figured I could probably get far enough for it to return a -1 if "tenth" wasn't > 4, but I don't know how I can get it to print x[0:dec] if it's < 5 and x[0:dec]+1 if it's > 4.
:/
Could someone please give me a nudge in the right direction?
This is a weird restriction, but you could do this:
x = str(x)
dec_index = x.find('.')
tenth_index = dec_index + 1
tenth_place = x[tenth_index] # will be a string of length 1
should_round_up = 5 + tenth_place.find('5') + tenth_place.find('6') + tenth_place.find('7') + tenth_place.find('8') + tenth_place.find('9')
print int(x[0:dec_index]) + should_round_up
What we do is look at the tenths place. Since .find() returns -1 if the argument isn't found, the sum of the .find() calls will be -4 if if the tenths place is 5, 6, 7, 8, or 9 (since one of the .find() calls will succeed and return 0), but will be -5 if the tenths place is 0, 1, 2, 3, or 4. We add 5 to that, so that should_round_up equals 1 if we should round up, and 0 otherwise. Add that to the whole number part, and we're done.
That said, if you weren't subject to this artificial restriction, you would do:
print round(x)
And move on with your life.
judging by the accepted answer you only expects floats so that is pretty trivial to solve:
x = 3.54159
# split on .
a, b = str(x).split(".")
# cast left side to int and add result of test for right side being greater or equal to 5
print(int(a) + (int(b) >= 5))
(int(b) > 5) will be either 1 or 0 i.e True/False so we either add 1 when right side is > .5 or flooring when it's < .5 and adding 0.
If you were doing it mathematically you just need to print(int(x+.5)), anything >= .5 will mean x will be rounded up and floored when it is < .5.
x = 3.54159
# split on .
a, b = str(x).split(".")
# cast left side to int and add result of test for right side being greater or equal to 5
print(int(a) + (int(b[0]) >= 5))
# above code will not work with 3.14567 and the number with having two or more digits after decimal
I think it's easier...
x = x + 0.5
intPart, decPart = str(x).split(".")
print intPart
Examples:
If x = 1, then it will become 1.5 and intPart will be 1.
If x = 1.1, then it will become 1.6 and intPart will be 1.
If x = 1.6, then it will become 2.1 and intPart will be 2.
Note: it will only work for positive numbers.
This code will round numbers to the nearest whole
without using conditionals
You can do it this way
x = 3.54159
x = x + 0.5 # This automatically takes care of the rounding
str_x = str(x) # Converting number x to string
dp = str_x.find('.') # Finding decimal point index
print str_x[:dp] # Printing upto but excluding decimal point
I did the same course at Udacity. solved it using the following code:
y = str(x)
decimal = y.find('.')
y_increment = y[decimal+1:]
print decimal
print y_increment
# Section below finds >5
check5 = y_increment.find('5',0,1)
check6 = y_increment.find('6',0,1)
check7 = y_increment.find('7',0,1)
check8 = y_increment.find('8',0,1)
check9 = y_increment.find('9',0,1)
yes_increment = (check5 + 1) + (check6 + 1) + (check7 + 1) + (check8 + 1) + (check9 + 1)
print check5, check6, check7, check8, check9
#Calculate rounding up
z = x + (yes_increment)
z = str(z)
final_decimal = z.find('.')
print z[:final_decimal]

While Loop to produce Mathematical Sequences?

I've been asked to do the following:
Using a while loop, you will write a program which will produce the following mathematical sequence:
1 * 9 + 2 = 11(you will compute this number)
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
Then your program should run as far as the results contain only "1"s. You can build your numbers as string, then convert to ints before calculation. Then you can convert the result back to a string to see if it contains all "1"s.
Sample Output:
1 * 9 + 2 = 11
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
1234 * 9 + 5 = 11111
Here is my code:
def main():
Current = 1
Next = 2
Addition = 2
output = funcCalculation(Current, Addition)
while (verifyAllOnes(output) == True):
print(output)
#string concat to get new current number
Current = int(str(Current) + str(Next))
Addition += 1
Next += 1
output = funcCalculation(Current, Next)
def funcCalculation(a,b):
return (a * 9 + b)
def verifyAllOnes(val):
Num_str = str(val)
for ch in Num_str:
if(str(ch)!= "1"):
return False
return True
main()
The bug is that the formula isn't printing next to the series of ones on each line. What am I doing wrong?
Pseudo-code:
a = 1
b = 2
result = a * 9 + b
while string representation of result contains only 1s:
a = concat a with the old value of b, as a number
b = b + 1
result = a * 9 + b
This can be literally converted into Python code.
Testing all ones
Well, for starters, here is one easy way to check that the value is all ones:
def only_ones(n):
n_str = str(n)
return set(n_str) == set(['1'])
You could do something more "mathy", but I'm not sure that it would be any faster. It would much more easily
generalize to other bases (than 10) if that's something you were interested in though
def only_ones(n):
return (n % 10 == 1) and (n == 1 or only_ones2(n / 10))
Uncertainty about how to generate the specific recurrence relation...
As for actually solving the problem though, it's actually not clear what the sequence should be.
What comes next?
123456
1234567
12345678
123456789
?
Is it 1234567890? Or 12345678910? Or 1234567900?
Without answering this, it's not possible to solve the problem in any general way (unless in fact the 111..s
terminate before you get to this issue).
I'm going to go with the most mathematically appealing assumption, which is that the value in question is the
sum of all the 11111... values before it (note that 12 = 11 + 1, 123 = 111 + 11 + 1, 1234 = 1111 + 111 + 11 + 1, etc...).
A solution
In this case, you could do something along these lines:
def sequence_gen():
a = 1
b = 1
i = 2
while only_ones(b):
yield b
b = a*9 + i
a += b
i += 1
Notice that I've put this in a generator in order to make it easier to only grab as many results from this
sequence as you actually want. It's entirely possible that this is an infinite sequence, so actually running
the while code by itself might take a while ;-)
s = sequence_gen()
s.next() #=> 1
s.next() #=> 11
A generator gives you a lot of flexibility for things like this. For instance, you could grab the first 10 values of the sequence using the itertools.islice
function:
import itertools as it
s = sequence_gen()
xs = [x for x in it.islice(s, 10)]
print xs

Categories