Solved

for loop

Posted on 2011-09-06
7
236 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
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 50 total points
ID: 36488039
Hi, should be as follows:

for x in range(0,100):
   y[x] = math.sin( i * 20 )
0
ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

 
LVL 28

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 28

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 28

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
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 …
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…

803 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