The discussion revolves around a programming assignment that requires creating two vector arrays based on user input and calculating their scalar product. The user is prompted to enter a positive integer N, with a restriction that N must not exceed 20. The main issues discussed include correcting the logic for handling the input, properly appending values to the vectors, and ensuring that the final output only displays the completed vectors and their scalar product rather than intermediate steps. Participants emphasize the importance of understanding list manipulation and Python's loop structures, as well as the need to avoid unnecessary memory usage by eliminating redundant arrays. Ultimately, the conversation highlights the significance of proper coding practices and debugging techniques in achieving the desired output.
Take as input from the user an integer N. We don't want the user to enter very large integers, so exit with an error message if N>20. You may assume that N is an integer (and not a real number) and also that it is positive. Make two vectors v1 and v2 using v1.append() and v2.append() to fill in these vectors in the following way:
nth element of v1 should be cos(pi*n/16)
nth element of v2 should be sin(pi*n/21)
Finally find the scalar product of the two vectors.
Homework Equations
The Attempt at a Solution
Here is my code
Python:
#!/usr/bin/python
N=int(input('Enter integer: '))
if N>20:
print ('error')
exit ()
elif N<20:
v1=[]
for n in range (1,N+1):
import math
x=math.cos(math.pi*n / 16)
v1.append(x)
print (v1)
Problem is it takes v1 for every n so its like v1=[x1] then v1=[x1,x2] v1=[x1,x2,x3] it prints all like this
But I just only want the last one. How can I choose it ?
Problem is it takes v1 for every n so its like v1=[x1] then v1=[x1,x2] v1=[x1,x2,x3] it prints all like this
But I just only want the last one. How can I choose it ?
It's not clear to me what you're asking -- the "last one" of what?
First interpretation: you just want the last element of an array
use of the minus one index position gets the last element in your array / list.
Second interpretation: you want the final print stmt only
just move the print statement out of that for loop by 'de-indenting' it
Important point:
Your if statements are incorrect. As is they don't address the N=20 case (contra to problem directions). If you choose to do an "elif" you need to get the inequalities right -- just using an "else" statement is easier and less error prone here, I think.
Second interpretation: you want the final print stmt only
just move the print statement out of that for loop by 'de-indenting' it
Not exactly.. umm I want only the last array then I ll do the same thing for v2 then I ll multiply those.
"Important point:
Your if statements are incorrect. As is they don't address the N=20 case (contra to problem directions). If you choose to do an "elif" you need to get the inequalities right -- just using an "else" statement is easier and less error prone here, I think."
I can't tell whether the real issue is understanding how to manipulate a list, or understanding how for loops work, or understanding how whitespace works in Python, or something else.
Arman777 said:
I want only the last array then I ll do the same thing for v2 then I ll multiply those.
For avoidance of doubt, there is no "last array" here. The way to think about it is: your code only has one array (actually a list) that you are appending to, via a command called "append". There aren't multiple arrays here -- just one, that you're growing over time via the 'append' operation. After that for loop is done, you only have that 'fully grown' list.
If you 'de-indent' the print stmt, you won't be doing a print at every iteration of the for loop, and instead you'll just do a single print once you've completed the for loop (and only see the 'fully grown' list).
- - - -
sometimes just playing around with this stuff, as well as some examples in books, can be quite helpful. Allen Downey has some nice books that he makes freely available via the publisher. E.g. you may enjoy "Think Python", here:
For avoidance of doubt, there is no "last array" here. The way to think about it is: your code only has one array (actually a list) that you are appending to, via a command called "append". There aren't multiple arrays here -- just one, that you're growing over time via the 'append' operation. After that for loop is done, you only have that 'fully grown' list.
I see your point..actually I also didnt fully understand what question asks us ? Since now I have a feeling that my approach is wrong to answer the question.
Okay could you just show me a way to sum the this A for every z
Code:
#!/usr/bin/python
N=int(input('Enter integer: '))
if N>20:
print ('error')
exit ()
elif N<=20:
v1=[]
for n in range (1,N+1):
import math
x=math.cos(math.pi*n / 16)
v1.append(x)
v2=[]
for y in range (1,N+1):
k=math.sin(math.pi*y / 21)
v2.append(k)
for z in range (1,N):
A=v1[z]*v2[z]
h=sum(v1[z]*v2[z])
print (h)
suppose I have a vector ##\mathbf v## with ##m## entries in it and I want to get the sum. I can of course use a built-in function (which is preferable once you get comfortable with all of the basics), but I can also create a running sum.
Python:
running_sum = 0
for i in range(m):
running_sum += v[i]
# for loop has terminated at this point
print(running_sum)
you should be able to translate this to your problem
You may assume that N is an integer (and not a real number)
Minor point: Integers are real numbers. They just don't happen to have a fractional part.
I've added some comments on your code. Look for the >> characters.
Arman777 said:
Okay could you just show me a way to sum the this A for every z
Code:
#!/usr/bin/python
N=int(input('Enter integer: '))
if N>20:
print ('error')
exit ()
elif N<=20: ;; >> Or you could just use else:
v1=[]
for n in range (1,N+1):
import math ;; >> This is very inefficient. This import statement should be up at the top, not inside a loop
x=math.cos(math.pi*n / 16)
v1.append(x)
v2=[]
for y in range (1,N+1):
k=math.sin(math.pi*y / 21)
v2.append(k)
for z in range (1,N): ;; >> Why range(1, N)? Your other loops have range(1, N+1)
A=v1[z]*v2[z]
h=sum(v1[z]*v2[z]) ;;>> See Stone Temple Python's hint on how to do this
print (h) ;;>> Do you really want to print the sum in each loop iteration? You need to do this only once, after the loop finishes.
I am really stucked
For the record, there is no such word in English as "stucked."
#!/usr/bin/python
N=int(input('Enter integer: '))
if N>20:
print ('error')
exit ()
elif N<20:
import math
v1=[]
for n in range (1,N+1):
x=math.cos(math.pi*n / 16)
v1.append(x)
v2=[]
for y in range (1,N+1):
k=math.sin(math.pi*y / 21)
v2.append(k)
v=[]
for z in range (0,N):
A=v1[z]*v2[z]
v.append(A)
running_sum = 0
for i in range(0,N+1):
running_sum += A[i]
print(running_sum)
What does this mean? Does it mean that you got your code to work?
Here's how I would do the problem.
For an input value of N, I fill in the first array as v1(0), v1(1), ..., v1(N - 1), and the same for the v2 array.
I removed some of the code you had that was inside a loop, moving it outside the loop so that it would run only once.
I also simplified your code by reusing variables instead of introducing new variable names.
I also added comments along the way to help the reader understant what I was doing. This is a good habit to get into,
and is probably one that your instructor wants you to use.
Finally, there was a bug in your code with "if N > 20:" and "elif N < 20:" Do you know what the bug is?
Python:
import math
N=int(input('Enter integer: '))
if N>20:
print ('error')
exit ()
#elif N<20: ## What happens if you enter 20?
else:
v1=[]
# Fill array v1 with values of cos(pi * n/16)
for n in range (0,N):
x=math.cos(math.pi*n / 16)
v1.append(x)
# After array is filled, print out its values
print("v1: ", v1)
v2=[]
# Fill array v2 with values of sin(pi * n/21)
for n in range (0,N):
x=math.sin(math.pi*n / 21)
v2.append(x)
# After array is filled, print out its values
print("v2: ", v2)
running_sum = 0
# Calculate dot product of arrays v1 and v2
for n in range (0,N):
running_sum += v1[n] * v2[n]
# Print the dot product value
print(running_sum)
What does this mean? Does it mean that you got your code to work?
yep
Mark44 said:
Do you know what the bug is?
why bug ?
Why print all the data ? If N=20 then I mean there would be 40 lines ?
Python:
#!/usr/bin/python
N=int(input('Enter integer: '))
if N>20:
print ('error')
exit ()
elif N<=20:
import math
v1=[]
for n in range (1,N+1):
x=math.cos(math.pi*n / 16)
v1.append(x)
v2=[]
for y in range (1,N+1):
k=math.sin(math.pi*y / 21)
v2.append(k)
v=[]
for z in range (0,N):
A=v1[z]*v2[z]
v.append(A)
sm = sum(v[0:N])
print(sm)
In your previous code (post #11) you had
if N > 20:
<stuff>
elif N < 20:
<other stuff>
What happens if the user enters 20?
Arman777 said:
Why print all the data ? If N=20 then I mean there would be 40 lines ?
I added the first two print statements mostly as sanity checks, just to see if I was getting reasonable values in the two arrays.
No, you don't get 40 lines. I entered a value of 6, so both arrays were printed on one line. If you have larger values, you'll get longer lines that wrap, but you won't get 40 separate lines.
Your code:
Python:
for n in range (1,N+1):
x=math.cos(math.pi*n / 16)
v1.append(x)
v2=[]
for y in range (1,N+1):
k=math.sin(math.pi*y / 21)
v2.append(k)
v=[]
You could use "for n in range (0, N) for both loops. You don't need two separate loop control variables, and you can run your loops for n = 0, 1, 2, ..., N-1
You should NOT have v2 = [] as part of the first loop. In other words, this line should NOT be indented.
You should also NOT have v = [] as part of the 2nd loop.
In the second loop, you don't need a different variable k -- you can re-use x.
Finally, you don't need to have a third array v[], as this is a waste of computer memory. Instead, you can do this, which is pretty much what Stone Temple Python was saying:
Python:
# Calculate dot product of arrays v1 and v2
for n in range (0,N):
running_sum += v1[n] * v2[n]
Finally, you don't need to have a third array v[], as this is a waste of computer memory. Instead, you can do this, which is pretty much what Stone Temple Python was saying:
Well I tried that but I couldn't do it
Mark44 said:
You should NOT have v2 = [] as part of the first loop. In other words, this line should NOT be indented.
You should also NOT have v = [] as part of the 2nd loop.
Is that changes anything ?
Mark44 said:
In your previous code (post #11) you had
if N > 20:
<stuff>
elif N < 20:
<other stuff>
What happens if the user enters 20?
I see your point now. Well, you are right 20 gives me the error. I can make elif N<=21 or just else , I think both are same?
Mark44 said:
You should NOT have v2 = [] as part of the first loop. In other words, this line should NOT be indented.
Okay, I changed that well, does it make difference? don't get me wrong I am really asking since I want to learn
I did a check to see that our codes give the same result or not and they don't I wonder why?
There are some special cases where you are doing a padding at index zero for an N+1 length array, but those are special cases and don't apply here.
------
A general comment: you are deep in the weeds on indexing and this is predictably causing problems. Things like using a specific (and wrong) elif statement, when in fact you should just be using an else statement.
And while Mark's comment that creating an extra array ##v## is wasteful is more to the point for this exercise, I wanted to point out that if you did need to create ##v## for some reason and wanted to sum all of the entries in ##v##, you should never use
Python:
sm = sum(v[0:N])
As this is setting you up for subtle indexing issues, and makes the reader strain to confirm what is being summed over
instead just use
Python:
sm = sum(v)
which is a built-in function that sums over everything -- you only use indexing to 'grab' some proper sub-portion of the whole array and then sum said the thing you 'grabbed'.
- - - -
if you have any small projects similar to this that you're interested in, you'd be wise to do them now, even though the assignment is done. Just repeatedly doing coding projects day in and out and getting a little better each time, really adds up.
Finally, you don't need to have a third array v[], as this is a waste of computer memory. Instead, you can do this, which is pretty much what Stone Temple Python was saying:
Arman777 said:
Well I tried that but I couldn't do it.
Look at the bottom of my code in post #13.
Mark44 said:
You should NOT have v2 = [] as part of the first loop. In other words, this line should NOT be indented.
You should also NOT have v = [] as part of the 2nd loop.
Arman777 said:
Is that changes anything ?.
Yes. You are essentially declaring your two arrays in each loop iteration. This is inefficient.
Mark44 said:
In your previous code (post #11) you had
if N > 20:
<stuff>
elif N < 20:
<other stuff>
What happens if the user enters 20?
Arman777 said:
I see your point now. Well, you are right 20 gives me the error. I can make elif N<=21 or just else , I think both are same?.
No, "elif N <= 21:" is not the same.
In post #14 you had
if N > 20:
<do stuff>
elif N <= 20:
<do other stuff>
This is OK, but here's a nicer way to do things:
if N > 20:
<do stuff>
else:
<do other stuff>
If N is larger than 20, you want to bail out, otherwise continue on with your calculations.
Mark44 said:
You should NOT have v2 = [] as part of the first loop. In other words, this line should NOT be indented.
Arman777 said:
Okay, I changed that well, does it make difference? don't get me wrong I am really asking since I want to learn.
That's good that you want to learn. My comments are intended to be constructive criticism, to help you understand your code better, and to write better code. Unlike C, C++, C#, Java, and many other languages, Python doesn't use braces { } to delimit blocks of code. Instead, Python uses indentation.
In Python, there's a difference between these two snippets.
1.
Python:
sum = 0
for i in range(0, 6)
sum += i
print(i)
2,
Python:
sum = 0
for i in range(0, 6)
sum += i
print(i)
In the first example, the print statement executes 6 times. In the second example, the print statement executes only once.
Arman777 said:
I did a check to see that our codes give the same result or not and they don't I wonder why?.
Because my indexes range from 0 through N - 1, and yours range from 1 through N -- that's why.
The problem statement didn't specify whether n should start from 0 or from 1. I think the intent was that it should start from 0, but you would have to ask your instructor which of these was intended.
if you have any small projects similar to this that you're interested in, you'd be wise to do them now, even though the assignment is done. Just repeatedly doing coding projects day in and out and getting a little better each time, really adds up.
Like what can I do, any examples? I started to like the coding..it takes time for me but its fun
Also, I 'll be more careful in ranges, thanks for the info also for the sum thing.
Mark44 said:
Look at the bottom of my code in post #13.
I understand now ..I couldn't think of it before or I didn't know it actually. (How to use it, even stonetemple said it...)
Mark44 said:
In the first example, the print statement executes 6 times. In the second example, the print statement executes only once.
oh.I get it know thanks for that.
Mark44 said:
The problem statement didn't specify whether n should start from 0 or from 1. I think the intent was that it should start from 0, but you would have to ask your instructor which of these was intended.
The beginning problems are easy but it gets progressively more difficult. (Too many prime number problems in there overall for my tastes but there are a lot of other problems as well.)
One of my original interests in coding was probability related problems -- e.g. coding an option pricing model (don't do this if you don't already know option pricing) or solving/ estimating little probability puzzles -- e.g. the riddler at 538 has a lot of problems that are amenable to running a simulation https://fivethirtyeight.com/tag/the-riddler/
There's a lot of other stuff out there -- just find little projects or puzzles that have a somewhat simple but repetitive quantitative component -- computers are great for that kind of thing, provided you write correct code, of course
MIT has a great free sequence on edx.org, as well 6.001x I think is their intro to CS with python
The beginning problems are easy but it gets progressively more difficult. (Too many prime number problems in there overall for my tastes but there are a lot of other problems as well.)
I started to do first problem but I am stuck :)
should I post the problem here ?
edit:Okay, I solved it :) no need
edit 1: It seems a great site thanks for sharing.
Yes. Create a new thread for the problem in this forum as it's a new problem. Mark or I or another member, will likely be able to help.
(As always, try to use the HW template, show your first or second cut at attempting the problem, and so on.) A lot of this stuff really is iterative -- just keep on putting in the (thoughtful) time, and the problem will eventually yield to you.