Looping Program Problem -- create and fill in two vector arrays....

In summary: No problem. Here's an example of how to do it: v1=[]v2=[]for n in range (1, N+1): import math x=math.cos(math.pi*n / 16) v1.append(x) v2.append(x)problem is that it takes v1 for every n so its like v1=[x1] then v1=[x1,x2] v1=[x1,x2,x3] it prints all like thisBut
  • #1
Arman777
Insights Author
Gold Member
2,168
192

Homework Statement



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 ?

Thanks
 
Last edited by a moderator:
Physics news on Phys.org
  • #2
Arman777 said:
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.
 
Last edited:
  • Like
Likes Arman777
  • #3
StoneTemplePython said:
It's not clear to me what you're asking -- the "last one" of what?
Adsız.png

For example İts like this for N=6 there's 6 v1 vector. but I only want the last one (I think that's the right way to solve the problem)
 

Attachments

  • Adsız.png
    Adsız.png
    13.8 KB · Views: 314
  • #4
StoneTemplePython said:
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 changed my equality..thanks for warning
 
  • #5
StoneTemplePython said:
just move the print statement out of that for loop by 'de-indenting' it
Oh wait that's the answer I guess
 
  • #6
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:

http://greenteapress.com/wp/think-python-2e/
 
  • #7
StoneTemplePython said:
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.
 
  • #8
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)

I am really stucked

last lines
 
  • #9
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
 
  • #10
Arman777 said:
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."
 
  • #11
Okay here my last work , please help me..

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)
                  running_sum = 0
      for i in range(0,N+1):
          running_sum += A[i]
          print(running_sum)
 

Attachments

  • Adsız 1.png
    Adsız 1.png
    29 KB · Views: 334
  • Adsız.png
    Adsız.png
    34.8 KB · Views: 312
  • #12
Okay I did it
 
  • #13
Arman777 said:
Okay I did it
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)
 
  • #14
Mark44 said:
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)

my code
 
  • #15
Arman777 said:
why bug ?
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]
 
  • #16
Mark44 said:
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?
Adsız 3.png


the upper one is mine and the lower is yours.
 

Attachments

  • Adsız 3.png
    Adsız 3.png
    45.3 KB · Views: 341
  • #17
Arman777 said:
I did a check to see that our codes give the same result or not and they don't I wonder why?
Cause my range starts from 1...

I have already send it like hours ago , but its nice to see my mistakes
 
  • #18
Arman777 said:
Cause my range starts from 1...

Why did you start indexing at one in your ranges?

note: in python, you should basically never do

Python:
 for y in range (1,N+1):

it should almost always be

Python:
 for y in range (N):

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.
 
  • Like
Likes Arman777
  • #19
Mark44 said:
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.
 
  • Like
Likes Arman777
  • #20
StoneTemplePython said:
Why did you start indexing at one in your ranges?
No idea :)
StoneTemplePython said:
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.
Yes, I also think it should start from zero.

I learned the general idea I guess. Thanks
 
  • #21
Arman777 said:
No idea :)

Like what can I do, any examples? I started to like the coding..it takes time for me but its fun

Well, you may enjoy https://projecteuler.net/

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
 
  • Like
Likes Arman777
  • #22
StoneTemplePython said:
Well, you may enjoy https://projecteuler.net/

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.
 
Last edited:
  • Like
Likes StoneTemplePython
  • #23
Arman777 said:
I started to do first problem but I am stuck :)

should I post the problem here ?

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.
 

1. What is a looping program?

A looping program is a type of computer program that repeats a sequence of instructions until a certain condition is met. It allows for efficient repetition of tasks without having to write the same code multiple times.

2. How do you create a vector array in a looping program?

To create a vector array in a looping program, you would first declare the array and specify the data type of the elements. Then, using a for loop, you can fill in the array with values by assigning them to each index of the array.

3. How do you fill in two vector arrays using a looping program?

To fill in two vector arrays using a looping program, you would use nested for loops. The outer loop would iterate through the first array, and the inner loop would iterate through the second array, assigning values to each index of both arrays.

4. What is the purpose of using a looping program for creating and filling in vector arrays?

The purpose of using a looping program for creating and filling in vector arrays is to automate the process and make it more efficient. It allows for repetitive tasks to be completed quickly and accurately, reducing the chances of human error.

5. What are some common mistakes to avoid when creating and filling in vector arrays with a looping program?

Some common mistakes to avoid when creating and filling in vector arrays with a looping program include not properly initializing the array, not using the correct variable for the loop counter, and not setting the correct conditions for the loop to terminate. It is also important to make sure the arrays are the same size and that the correct indexes are being assigned values in the correct order.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
9
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
6K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
5K
  • Engineering and Comp Sci Homework Help
Replies
23
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
Back
Top