Just want to check if the way i have used the assignment expression in python 3.8 program is correct or not - python-3.8

According to Heron's formula for finding area of a triangle , if the sides of a triangle are a, b & c is :
s = (a+b+c) / 2
area =sqrt( s * (s-a) * (s-b) * (s-c)) # sqrt means square root
so for finding the area of the triangle using Heron's formula in Python, if I write code like this, will it be a valid practise? I have used assignment expression while calculating the area.
a = int(input("Enter value of first side")) # Assuming value is integer
b = int(input("Enter value of second side")) # Assuming value is integer
c = int(input("Enter value of third side")) # Assuming value is integer
area = ((s := (a+b+c) /2) *(s -a)*(s-b)*(s-c))**0.5
print("Area of the triangle is", area)

Yes, program counts correct. There is a one drawback in input: I recommend to add '\n' in input because it is uncomfortable to enter values without any space near text. In this code I fixed that. But you need to add checking if sides can make triangle.
a = int(input("Enter value of first side")) // Assuming value is integer
b = int(input("Enter value of second side")) // Assuming value is integer
c = int(input("Enter value of third side")) // Assuming value is integer
area = ((s := (a+b+c) /2) *(s -a)*(s-b)*(s-c))**0.5
print("Area of the triangle is", area)

Related

i am new, program gives error "there are no type variables left in list"

How the game works is that there is a 3-digit number, and you have to guess it. If you guess a digit in the right spot, you get a strike, and if you guess a digit but in the wrong spot you get a ball. I've coded it like this.
x = random.randint(1, 9)
y = random.randint(1, 9)
z = random.randint(1, 9)
userguessunlisted = input('What number do you want to guess?')
numbertoguess = list[x, y, z]
userguess = list(userguessunlisted)
b = 0
s = 0
while 0 == 0:
if userguess[0] == numbertoguess[0]:
s = s + 1
if userguess[0] == numbertoguess[1]:
b = b + 1
if userguess[0] == numbertoguess[2]:
b = b + 1
if userguess[1] == numbertoguess[0]:
b = b + 1
if userguess[1] == numbertoguess[1]:
s = s + 1
if userguess[1] == numbertoguess[2]:
b = b + 1
if userguess[2] == numbertoguess[0]:
b = b + 1
if userguess[2] == numbertoguess[1]:
b = b + 1
if userguess[2] == numbertoguess[2]:
s = s + 1
print(s + "S", b + "B")
if s != 3:
b = 0
s = 0
else:
print('you win!')
break
When you said list[x, y, z] on line 5, you used square brackets, which python interprets to be a type annotation. For example, if I wanted to specify that a variable is a list of ints, I could say
my_list_of_ints: list[int] = [1, 2, 3]
I think what you meant to do is create a new list from x, y, and z. One way to do this is
numbertoguess = list([x, y, z])
which is probably what you meant to write. This is valid because the list function takes an iterable as its one and only argument.
However, the list portion is redundant; square brackets on the right-hand side of an assignment statement already means "create a list with this content," so instead you should simply say
numbertoguess = [x, y, z]
A few other notes:
input will return a string, but you are comparing that string to integers further down, so none of the comparisons will ever be true. What you want to say is something like the following:
while True:
try:
userguessunlisted = int(input('What number do you want to guess?'))
except:
continue
break
What this code does is attempts to parse the string returned from input into an int. If it fails to do so, which would happen if the user inputted something other than a valid integer, an exception would be thrown, and the except block would be entered. continue means go to the top of the loop, so the input line runs repeatedly until a valid int is entered. When that happens, the except block is skipped, so break runs, which means "exit the loop."
userguessunlisted is only ever going to contain 1 number as written, so userguess will be a list of length 1, and all of the comparisons using userguess[1] and userguess[2] will throw an IndexError. Try to figure out how to wrap the code from (1) in another loop to gather multiple guesses from the user. Hint: use a for loop with range.
It might also be that you meant for the user to input a 3-digit number all at once. In that case, you can use a list comprehension to grab each character from the input and parse it into a separate int. This is probably a bit complicated for a beginner, so I'll help you out:
[int(char) for char in input('What number do you want to guess?')]
print(s + "S", b + "B") will throw TypeError: unsupported operand type(s) for +: 'int' and 'str'. There are lots of ways to combine non-string types with strings, but the most modern way is using f-strings. For example, to combine s with "S", you can say f"{s}S".
When adding some amount to a variable, instead of saying e.g. b = b + 1, you can use the += operator to more concisely say b += 1.
It's idiomatic in python to use snake_case for variables and Pascal case for classes. So instead of writing e.g. numbertoguess, you should use number_to_guess. This makes your code more readable and familiar to other python programmers.
Happy coding!

Why does the 'i' need to be divided by 2 in caculating positional encoding?

In this transformer tutorial:
https://www.tensorflow.org/text/tutorials/transformer
def get_angles(pos, i, d_model):
angle_rates = 1 / np.power(10000, (2 * (i//2)) / np.float32(d_model))
return pos * angle_rates
I don't understand why 'i//2' is used, since in the original formula there is no specification of the integer division.
So what's the purpose of i//2?
according to the formula
PE(pos, 2i) = sin(1/100000^(2i /D) , PE(pos, 2i+1) = cos(1/100000^(2i
/D)
As you can see, for odd row, 2i -> 2i, for even row 2i+1 -> 2i, for example, a word embedding with [0,1,2,3,4,5,6,7] should transfer to [0,0,1,1,2,2,3,3], there is where i//2 comes from.

Lua moving table up causing nil value error

I have a table of tables which represents a 65*65 square grid where each element is integer values. It represents the area around an actor and the actor can move in the four cardinal directions and as they do I need the table to move with them so they remain in the center square 33,33.
Rather than moving the elements of the table I instead have two pointers tableIndex.left and tableIndex.down which store the indexes of the far left column of the bottom row respectively, they both start at 65. I have three helper functions to perform operations on the table, all take the arguments x1,x2,y1,y2 where x1 and y1 are the co-ordinates to start the function at and x2 and y2 are the co ordinates to end the function.
These functions are tableInit which creates tables in all the values between x1 and x2. zero table which fills all of the entries in the specified range with 0 and clear table which sets all the entries in the specified range to nil.
function movetable(direction)
--function to move our probability histogram
-- 0 is up, 1 is right, 2 is down, 3 is left
--as a note robotSpeed = 1
if direction == 0 then
tableIndex.down += robotSpeed
zerotable(tableIndex.left,tableIndex.left+64,tableIndex.down+64,tableIndex.down+64)
cleartable(tableIndex.left,tableIndex.left+64,tableIndex.down-1,tableIndex.down-1)
elseif direction == 1 then
tableIndex.left += robotSpeed
tableInit(tableIndex.left+64,tableIndex.left+64)
zerotable(tableIndex.left+64,tableIndex.left+64,tableIndex.down,tableIndex.down+64)
cleartable(tableIndex.left-1,tableIndex.left-1,tableIndex.down,tableIndex.down+64)
elseif direction == 2 then
tableIndex.down -= robotSpeed
zerotable(tableIndex.left,tableIndex.left+64,tableIndex.down,tableIndex.down)
cleartable(tableIndex.left,tableIndex.left+64,tableIndex.down+65,tableIndex.down+65)
else
tableIndex.left -= robotSpeed
tableInit(tableIndex.left,tableIndex.left)
zerotable(tableIndex.left,tableIndex.left,tableIndex.down,tableIndex.down+64)
cleartable(tableIndex.left+65,tableIndex.left+65,tableIndex.down,tableIndex.down+64)
end
end
The table is called later in the program,in the following section of code, which is where the error is thrown "Attempt to perform arithmetic on field '?' a nil value. This occurs when i and j are 0. This only occurs after the table has last moved up so dir==0 and the error ceases to exist if I comment out the cleartable call in my movetable function for the case when dir==0.
for i=0,64 do
for j=0,64 do
--Robot is at 33 33 so we know there isnt an obstacle here
if i ~= 32 and j ~= 32 then
--This is the equation from the paper which tells us which direction the result is in
local tan = atan2(i-33,j-33)+0.25
if (tan > 1) tan = tan-1
local dInD = flr(360*tan)
--Our polar histogram has sectors ALPHA degrees wide, this rounds the direction down to a multiple of
--the sector size so we can use it as an index
local dir = dInD - dInD%ALPHA
polarHist[dir] += certaintyTable[tableIndex.left+i][tableIndex.down+j]
end
end
As a note I dont have access to the standard lua libraries.
and here is cleartable in case I am doing that wrong
function cleartable(x1,x2,y1,y2)
if x1 == x2 then
for j=y1,y2 do
certaintyTable[x1][j] = nil
end
elseif y1==y2 then
for i=x1,x2 do
certaintyTable[i][y1] = nil
end
else
for i=x1,x2 do
for j=y1,y2 do
certaintyTable[i][j] = nil
end
end
end
end
Thanks for looking at my problem

mathematica getting input from user

'm new to mathematica. i have a small project: get an equation , a number n, a number x and a number y and a number h, then using euler formula calculate nTh iteration ... My code is :
f[x_,y_]=input["Please input f(x,y):"]
n=input["Please input number of iterations:"]
x0=input["Please input initial value x0:"]
y0=input["Please input initial value y0:"]
h=input["please input h:"]
For[i=0,i<n,i++,y0=y0+f[x0,y0]*h;x0=x0+h]
but when i copy this code in mathematica 9; it just print some texts and end . it did not get any input from user.just print this:
input["Please input f(x,y):"]
input["Please input number of iterations:"]
input["Please input initial value x0:"]
input["Please input initial value y0:"]
input["please input h:"]
and then end!
whould you help me ?
You should write it in two separate parts.
I would write an initialize variables part then the for loop.
Functions in Mathematica need a delayed equals := and to you recieved the outputs you did because Mathematica doesn't allow you to input while the code is running. you also should suppress the output with a ;
f[x_,y_]:= ; %%write in f(x,y)
n= ; %%input number of iterations
x0= ; %%input initial value x0
y0= ; %%input initial value y0
h= ; %%input h
An euler form of the solution is
euler:= Module[{ans, i, x, y, nsteps},
ans = {{x0,y0}};x=x0;y=y0;nsteps=n;
Do[(y=y+h*f[x,y];
x=x+h; ans=Append[and,{x,y}]),{i,1,nsteps}];ans]
To view the euler forumal result do...
eulerans1 = euler

Plot a third point past the two previously plotted points. Cocos2d

Ok so let me try to explain this the best way that i can.
I have two points plotted 'A' and 'B' and I am trying to plot a third point 'C' so that it is past point 'B' but along the same slope. I have the angle of the line and I would post some code but I really have no idea where to begin.
any help would be awesome!
Just a little code that i do have
CGPoint vector = ccpSub(touchedPoint, fixedPoint);
CGFloat rotateAngle = -ccpToAngle(vector);
Assuming that by this you mean you need a 3rd point C added such that all the points are colinear, all you need to do is calculate the vector that takes you from A to B, and then generate a new point by adding multiples of this vector to the point B. Choose the multiple based on the distance you want C to be from B.
As an example, say A = (2,2), B = (4,3). Then the vector from A to B is given by (2,1).
All you need to do then is work out how far your new point is from B and add a multiple K*(2,1) to your point B where K is chosen to meet the requirements of your distance
I am assuming you are in 2D, but the same method would apply in higher dimensions
My math is rusty, but the linear equation is generally represented as y=m*x+b, where m is the slope, and b is the y-intercept. You can get m, the slope, by taking the difference of the y values and dividing that by the difference in the x values, e.g., if A = (2,2) and B = (4,3), then m is (3-2)/(4-2) or 0.5. Then, you can solve the linear equation for b, the y-intercept, i.e. b=y-m*x and then plug in either of the data points, e.g. if we plug in the x and y values for point A, you get b = 2 - 0.5 * 2 = 1. Now knowing the slope, m (0.5 in this example), and the y-intercept, b (1 in this example), you can calculate the y for any x value using y=m*x+b, in this case y=0.5*x+1.
So, if touchedPoint and fixedPoint are CGPoint, you can calculate the slope and y-intercept from fixedPoint and touchedPoint like so:
double m = (fixedPoint.y - touchedPoint.y) / (fixedPoint.x - touchedPoint.x);
double b = fixedPoint.y - m * fixedPoint.x;
Now, you don't say how you want to determine where this third point, C, is. But if you, for example, knew the x coordinate for this new point C, you can calculate the y coordinate that falls on the same line as follows:
CGPoint pointC;
pointC.x = 400; // or set this to whatever you want
pointC.y = m * pointC.x + b;