renaming a variable in loop using Jython - python

I apologize if this question has been answered already, but having programming for only a month or so, I was unable to identify an answer as it relates to my particular circumstance.
I will be taking slices from a list, and as I am taking slices from this list through a loop process, I want a particular variable that is assigned to the slices to change its name during each loop process so that I can randomly choose from these variables. So far I have been unable with my limited knowledge to come up with a way to change this variable's name (even something like x1, x2, x3 would be okay with me).
for i in range(30):
z = 0
measureList = [C4, D4, E4]
z = len(measureList)
a = measureList[x:x + z]
x = x + z

If I understand you correctly (which is highly unlikely), you'd like to access slices of a list starting at a random index to the end of the list.
Try this:
import random
my_list = [1, 2, 3, 4, 5]
n = len(my_list)
for _ in xrange(30):
start = random.randint(1, n-2)
a = my_list[start:]
Update
The problem I am having it that when I want to store these created melodies (basically slices from a list), usually a static variable will constantly overwrite the information contained in the melody that was generated in the previous pass of the loop.
I presume the "static variable" you're referring to is a. You can just store it in another list. This way you can access it after leaving the loop.
import random
my_list = [1, 2, 3, 4, 5]
n = len(my_list)
other_list = []
for _ in xrange(30):
start = random.randint(1, n-2)
a = my_list[start:]
other_list.append(a)

Related

Python Find the mean school assignment - What is a loop?

I have been working on this assignment for about 2 weeks and have nothing done. I am a starter at coding and my teacher is really not helping me with it. She redirects me to her videos that I have to learn from every time and will not directly tell or help me on how I can do it. Here are the instructions to the assignment (said in a video, but made it into text.
Find the mean
Create a program that finds the mean of a list of numbers.
Iterate through it, and instead of printing each item, you want to add them together.
Create a new variable inside of that, that takes the grand total when you add things together,
And then you have to divide it by the length of your array, for python/java script you’ll need to use the method that lets you know the length of your list.
Bonus point for kids who can find the median, to do that you need to sort your list and then you need to remove items from the right and the left until you only have one left
All you’re doing is you need to create a variable that is your list
Create another variable that is a empty one at the moment and be a number
Iterate through your list and add each of the numbers to the variable you created
Then divide the number by the number of items that you had in the list.
Here's what I've done so far.
num = [1, 2, 3, 4, 5, 6];
total = 0;
total = (num[0] + total)
total = (num[1] + total)
total = (num[2] + total)
total = (num[3] + total)
total = (num[4] + total)
total = (num[5] + total)
print(total)
However, she tells me I need to shorten down the total = (num[_] + total) parts into a loop. Here is how she is telling me to do a loop in one of her videos.
for x in ____: print(x)
or
for x in range(len(___)): print (x+1, ____[x])
there is also
while i < len(___):
print(___[i])
i = i + 1
I really don't understand how to do this so explain it like I'm a total noob.
First of all, loops in python are of two types.
while: a while loop executes the code in a body until a condition is true. For example:
i = 0
while(i < 5):
i = i + 1
executes i = i + 1 until i < 5 is true, meaning that when i will be equal to 5 the loop will terminate because its condition becomes false.
for: a for loop in python iterates over the items of any sequence, from the first to the last, and execute its body at each iteration.
Note: in both cases, by loop body I mean the indented code, in the example above the body is i = i + 5.
Iterating over a list. You can iterate over a list:
Using an index
As each position of the array is indexed with a positive number from 0 to the length of the array minus 1, you can access the positions of the array with an incremental index. So, for example:
i = 0
while i < len(arr):
print(arr[i])
i = i + 1
will access arr[0] in the first iteration, arr[1] in the second iteration and so on, up to arr[len(arr)-1] in the last iteration. Then, when i is further incremented, i = len(arr) and so the condition in the while loop (i < arr[i]) becomes false. So the loop is broken.
Using an iterator
I won't go in the details of how an iterator works under the surface since it may be too much to absorb for a beginner. However, what matters to you is the following. In Python you can use an iterator to write the condition of a for loop, as your teacher showed you in the example:
for x in arr:
print(x)
An iterator is intuitively an object that iterates over something that has the characteristic of being "iterable". Lists are not the only iterable elements in python, however they are probably the most important to know. Using an iterator on a list allows you to access in order all the elements of the list. The value of the element of the list is stored in the variable x at each iteration. Therefore:
iter 1: x = arr[0]
iter 2: x = arr[1]
...
iter len(arr)-1: x = arr[len(arr)-1]
Once all the elements of the list are accessed, the loop terminates.
Note: in python, the function range(n) creates an "iterable" from 0 to n-1, so the for loop
for i in range(len(arr)):
print(arr[i])
uses an iterator to create the sequence of values stored in i and then i is in turn used on the array arr to access its elements positionally.
Summing the elements. If you understand what I explained to you, it should be straightforward to write a loop to sum all the elements of a list. You initialize a variable sum=0 before the loop. Then, you add the element accessed as we saw above at each iteration to the variable sum. It will be something like:
sum = 0
for x in arr:
sum = sum + x
I will let you write an equivalent code with the other two methods I showed you and do the other points of the assignment by yourself. I am sure that once you'll understand how it works you'll be fine. I hope to have answered your question.
She wants you to loop through the list.
Python is really nice makes this easier than other languages.
I have an example below that is close to what you need but I do not want to do your homework for you.
listName = [4,8,4,7,84]
for currentListValue in listName:
#Do your calculating here...
#Example: tempVar = tempVar + (currentListValue * 2)
as mentioned in the comments w3schools is a good reference for python.

Finding a pair of values which add up to given sum

lst = [3, 4, 1, 2, 9]
givenSum = 12
table = {}
x = 0
y = 0
for i in range(0, len(lst)):
table[givenSum - lst[i]] = 1
i += 1
for x in table:
for y in table:
if (x + y) == givenSum:
print(x, "and", y, "is equal to", givenSum)
break
This is the output
9 and 3 is equal to 12
3 and 9 is equal to 12
I don't know why it's being shown up twice. I need to find a pair of values that add up to the given sum and this is the only way I could think of. I only want it to show up once though any ideas on how I can do that?
There are better solutions, but to fix your issue making minimal changes to your code:
lst = [3, 4, 1, 2, 9]
givenSum = 12
for x in range(0, len(lst) - 1):
for y in range(x + 1, len(lst)):
if lst[x] + lst[y] == givenSum:
print(lst[x], "and", lst[y], "is equal to", givenSum)
break
This will print
3 and 9 is equal to 12
Note that the redundant table is completely removed from the code.
If you run it for a better test case:
lst = [3, 4, 5, 6, 7, 1, 2, 9]
it will print
3 and 9 is equal to 12
5 and 7 is equal to 12
First, to address why the looping continues and gives a second output, break can only break out of its immediate loop. Since you have a nested loop, the break only stops the for y in table: inner loop, but allows for x in table outer loop to move onto it's next iteration. So eventually, x is able to take the value of 3 later on, thus giving you the two outputs you see.
So, if you need a way to stop the iteration entirely when a solution is found, you need to either chain the break statements using a for else syntax (which arguably might be tough to read) as follows,
for x in table:
for y in table:
if (x + y) == givenSum:
print(x, "and", y, "is equal to", givenSum)
break #breaks from inner loop
else: #for else syntax: this block runs if and only if there was no break encountered during looping.
continue #jumps the outer loop to next iteration
break #this break is set at outer loop's level. Essentially, we can only reach this portion if there is a break in the inner loop.
For else says: run through the whole iteration, and if no break is found, executes the code in the else block. Essentially, the "else" of a "for else" is like a "for - no break".
However, one easier alternative is to use a function with a return (which also makes it easier to read the code).
def find_given_sum(lst, givenSum):
table = {}
x = 0
y = 0
for i in range(0, len(lst)):
table[givenSum - lst[i]] = 1
i += 1
for x in table:
for y in table:
if (x + y) == givenSum:
print(x, "and", y, "is equal to", givenSum)
return #this returns immediately out of the function, thus stopping the iteration.
Also, you could just repeat the break condition, but repeating code is generally not a good practice.
Hope this helps address why the two outputs are being printed. Now, as for the solution itself, there's actually a much better way to solve this. It builds upon the idea of compliments, which you seem to have a sense of in your table. But it doesn't require iteration over the table itself. As a hint: the ideal solution runs in O(n) time. I will not discuss the ideal solution, but hope this prompts you to find the best approach.
Looping twice for n elements costs you O(N^2) time, which is inefficient for large lists. Modified and tested the code to use hash map/dictionary to store the list elements and now it will take only O(N) time.
Map = dict()
lst = [3, 4, 1, 2, 9]
givenSum = 12
for i in range(0, len(lst)):
rem=givenSum-lst[i]
if rem in Map:
print lst[i],lst[Map[rem]]
else:
Map[lst[i]]=i
Store the value of each list element into the map whenever it does not exist in the map.
At each iteration, take the difference between givenSum and current element at that iteration and then search for that difference in the Map.
If it exists it means the pair exists or else not.
In this approach you are running the loop only once, which takes O(N) time because accessing elements in hash map is O(1)/constant time.
Use itertools to get the result
import itertools
sum = 10
lst = [3, 4, 1, 2, 9]
ans = list(filter(lambda x : x[0]+x[1] == sum,itertools.combinations(lst, 2)))

How to add values into an empty list from a for loop in python?

The given python code is supposed to accept a number and make a list containing
all odd numbers between 0 and that number
n = int(input('Enter number : '))
i = 0
series = []
while (i <= n):
if (i % 2 != 0):
series += [i]
print('The list of odd numbers :\n')
for num in series:
print(num)
So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.
In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.
One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:
series.append(i)
Good luck with your learning!
Do a list-comprehension taking values out of range based on condition:
n = int(input('Enter number : '))
print([x for x in range(n) if x % 2])
Sample run:
Enter number : 10
[1, 3, 5, 7, 9]

How can I code loop in python

I have a problem with the loop in python. I want create a list x[X0,X1,....Xn], with this algorithm:
X1=X0-(5+X0*2); X2=X1-(5+X1*2);.....
I try this but the result is not correct.
a=list(np.empty(10))
a[0]=1
for i in range(10):
a.append(a[i]-(5+a[i]*2))
print (a [i])
If you manually iterating the result gives:
[1,-6,1,-6, ....]
But after loop it gives:
[1,-1.29074375768e-231,2.19254982219e-314,.....]
The loop are easy in C but I did not understand the functioning in Python, if you have an idea ?
The problem is that list(np.empty(10)) doesn't do what you think it does. You expect it to return a list with 10 zeros, but it actually returns a list of 10 "random" numbers (actually, it returns a list of 10 uninitialized values).
From numpy docs:
empty, unlike zeros, does not set the array values to zero, and may
therefore be marginally faster. On the other hand, it requires the
user to manually set all the values in the array, and should be used
with caution.
(emphasize mine)
Instead, you should simply create a list with a single element, 1, and go on from there:
a = [1]
for i in range(10):
a.append(a[i] - (5 + a[i] * 2))
print(a)
# [1, -6, 1, -6, 1, -6, 1, -6, 1, -6, 1]
There's no reason to start your list with anything more than the single element. In C, you have to decide up front how many elements you want in your list, but that's not the case in Python, so doing list(np.empty(10)) creates a list with ten pointless elements in it that are just getting in your way.
a = [1] # This creates a list that starts off with the element 1.
for i in range(10):
a.append(a[i] - (5 + a[i] * 2))
print (a[i])
They way you have arranged your equation will constantly print out -6, and 1, therefore:
a = [1]
iti = 0
while(True):
thing = a[iti]-(5+(a[iti]*2))
a.append(thing)
iti+=1
print(thing)
I chose not to use the for loop to show a more understandable example, but you can still use that if you like.
I suggest you read up on functions, lists and for loops in python, as from your question it appears that you do not understand them very well.
There are several reasons why your code isn't currently working, but they are all easy fixed.
Firstly, you initiate a list with a numpy list, which is unnecessary.
a = list(np.empty(10))
can simply become
a = list()
or even simpler,
a = []
Next up, not an error but a suggestion,
a[0] = 1
can be removed and instead when you initialize the list, place one as the first item
a = [1]
after that, your code should work. So in summary:
n = 10 # or whatever number you want
a = [1]
for i in range(n - 1):
a.append(a[i] - (5 + a[i] * 2))
and if you want it as a function:
def formula_list(n):
a = [1]
for i in range(n - 1):
a.append(a[i] - (5 + a[i] * 2))
return a

Handling multiple variables in python

Here's issue I am learning python newly i want to use loop for generating inputs from user which are then operated for some custom function (say Lcm or squaring them and returning ) so how to perform code
Consider
k,l=0,0
while l>=10:
n_k=input("Enter")
k=k+1
l=l+1
#Do something within for loop
#here problem begins
#lets say i am dividing each variable by c which is here in for loop
for c in range(somevalue,0,-1):
now how should i operate the variables clearly i have no intention writting n_0%c ,n_1%c etc
Any Help???
Instead of n_k being a single variable i think you want n to be a list. A list is just a bunch of variables stored together. For example the code:
n = [1, 4, 2]
print(n[0]) #0th element of the list
print(n[1]) #1st element of the list
print(n[2]) #2nd element of the list
outputs
1
4
2
the line n = [1, 4, 2] is just defining the list. The elements of the list are accessed using the n[index] notation.
In python you can also add elements to a list at any time using the append statement. To illustrate let's define an empty list and add some elements to it.
n = []
n.append(8)
Now if we try
print(n[0])
the code will print 8.
So let's say we wanted to square a list of numbers we receive from user input, we would write
n = []
k = 0
num_inputs = 10
while k < num_inputs:
n.append(input("Enter:"))
k = k + 1
k = 0
while k < num_inputs:
print(n[k] * n[k])
k = k + 1
Hope it helps.

Categories