?
Solved

for loop

Posted on 2011-09-06
7
Medium Priority
?
243 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
New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
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

649 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