?
Solved

for loop

Posted on 2011-09-06
7
Medium Priority
?
241 Views
Last Modified: 2012-05-12
Hi

Can anybody tell me how to convert the following c++ code to python:

for (int x =0; x < 100; ++x){
     y[x] = sin( i * 20 );
}
0
Comment
Question by:IssacJones
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 29

Accepted Solution

by:
pepr earned 800 total points
ID: 36488019
Try the following:

a.py
import math

y = []    # empty list used as empty dynamic aray
print y   # to visualize what we have before            
for x in xrange(100):
    y.append(math.sin(x * 20))
    
print y   # what is inside after
print '-' * 70

# The alternative approach to simulate better the array.  The list
# of 100 elements is created first.  Then the "normal" indexing
# can be used to access and modify the elements.
y = [0] * 100
print y   # to visualize what we have before            
for x in xrange(100):
    y[x] = math.sin(x * 20)
print y   # what is inside after

Open in new window

0
 

Author Comment

by:IssacJones
ID: 36488031
Hi pepr

As you can gather I'm learning Python so please forgive the novice questions.

I note you use xrange(100). What if I was using

for (int x=5; x<100; ++x)

I'm slightly surprised that the Python code is so different to C++. I was expecting more of an overlap e.g. Java, I believe, is more like C++.

As a matter of interest, why was Python written so differently?

Issac
0
 
LVL 5

Assisted Solution

by:zvytas
zvytas earned 200 total points
ID: 36488039
Hi, should be as follows:

for x in range(0,100):
   y[x] = math.sin( i * 20 )
0
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

 
LVL 29

Expert Comment

by:pepr
ID: 36488091
The Python for-loop construct is not the counted loop as in C/C++.  It is rather for_each kind of loop.  The xrange(100) returns the iterator that goes from 0 to 99.  You can also use the range(100) that returns the list of 0 to 99.  When the list is used in the for loop, it is to be iterated.  The effect is the same.  The xrange() will be more memory efficient for big sequences.

However, there is numpy package that is more optimized for working with arrays and matrices.
0
 
LVL 29

Expert Comment

by:pepr
ID: 36488120
I tried the matplotlib just now, but it requires also numpy, and I haven't found the numpy for my environment (Python 2.7 64-bit on Windows).  But you possibly can try the following:

b.py
import math
import matplotlib.pyplot as plt

y = [0] * 100
for x in xrange(100):
    y[x] = math.sin(x * 20)
 
plt.plot(y)
plt.ylabel('sin(x)')
plt.show()

Open in new window


I have no idea if it works and how.  It is taken directly from the tutorial http://matplotlib.sourceforge.net/users/pyplot_tutorial.html (combined with the above sin).
0
 
LVL 29

Expert Comment

by:pepr
ID: 36488144
More about the for loop.  The C/C++ loop is not actually a counted loop (in comparison with say Pascal for-loop).  It is rather generalized while-loop with initialization commands and the "next" written syntactically before the body.

The Python for-loop is more abstract.  It was designed to simplify looping through anything that supports iteration.  This way you can get elements of lists, elements of tuples, elements of strings, elements of sets, keys of dictionaries, lines of text files, and values of whatever containers that supports iteration.
0
 

Author Closing Comment

by:IssacJones
ID: 36488159
Thanks guys
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
Here I am using Python IDLE(GUI) to write a simple program and save it, so that we can just execute it in future. Because when we write any program and exit from Python then program that we have written will be lost. So for not losing our program we…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question