Solved

for loop

Posted on 2011-09-06
7
235 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
  • 4
  • 2
7 Comments
 
LVL 28

Accepted Solution

by:
pepr earned 200 total points
Comment Utility
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
Comment Utility
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 50 total points
Comment Utility
Hi, should be as follows:

for x in range(0,100):
   y[x] = math.sin( i * 20 )
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 28

Expert Comment

by:pepr
Comment Utility
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 28

Expert Comment

by:pepr
Comment Utility
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 28

Expert Comment

by:pepr
Comment Utility
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
Comment Utility
Thanks guys
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
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 if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

728 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now