using copy in iterations - python

something is not going right in my code below. I have a big for loop which handles some math. But in the for loop the following guys contribute to the end result.
say:
for i in range(N):
# The math goes here.
sumrfactor=0.0
for k in R_factor:
sumrfactor += k
# print(sumrfactor)
Rfactor_sum=0
for n in signal:
Rfactor_sum +=n
#print(Rfactor_sum)
r_factor = sumrfactor/Rfactor_sum
rfactor = [r_factor.copy()]
export = open('note.txt','w')
for n in rfactor:
export.write(str(n))
For each iteration I want to copy r_factor I need it for some further analysis, so I am expecting to get N number of r_factor at the end of the big for loop. But for some weird reason I keep getting the final value at the end of the mighty for loop. i.e. I get one value instead of an array. Please guys I need your help with this issue, I have no idea where the problem is at. When I open the note file there is always a single figure which obviously does not look right. Thanks guys in advance!

Your problem is that you don't append the value to the list. Change the line rfactor = [r_factor.copy()] to this:
rfactor.append(r_factor)

Related

Can I randomly generate numbers without the same number next to eachother?

My goal is to generate a series of random numbers without allowing the same number repeating next to eachother but allowing the same number twice like 1,2,1,2 but not 1,1,2,2 and I'm just not really sure how to accomplish this.
Something like this?
import random
list = []
list.append(random.randrange(50))
for i in range(50):
x = random.randrange(50)
while x == list[i]:
x = random.randrange(50)
list.append(x)
print(list)
Also you should post your own attempt. It gives everyone a good reference and starting point to help you out in a meaning full and focused way.

Python : Counting execution of recursive call

I am using Euler problems to test my understanding as I learn Python 3.x. After I cobble together a working solution to each problem, I find the posted solutions very illuminating and I can "absorb" new ideas after I have struggled myself. I am working on Euler 024 and I am trying a recursive approach. Now, in no ways do I believe my approach is the most efficient or most elegant, however, I successfully generate a full set of permutations, increasing in value (because I start with a sorted tuple) - which is one of the outputs I want. In addition, in order to find the millionth in the list (which is the other output I want, but can't yet get) I am trying to count how many there are each time I create a permutation and that's where I get stuck. In other words what I want to do is count the number of recursive calls each time I reach the base case, i.e. a completed permutation, not the total number of recursive calls. I have found on StackOverflow some very clear examples of counting number of executions of recursive calls but I am having no luck applying the idea to my code. Essentially my problems in my attempts so far are about "passing back" the count of the "completed" permutation using a return statement. I think I need to do that because the way my for loop creates the "stem" and "tail" tuples. At a high level, either I can't get the counter to increment (so it always comes out as "1" or "5") or the "nested return" just terminates the code after the first permutation is found, depending on where I place the return. Can anyone help insert the counting into my code?
First the "counting" code I found in SO that I am trying to use:
def recur(n, count=0):
if n == 0:
return "Finished count %s" % count
return recur(n-1, count+1)
print(recur(15))
Next is my permutation code with no counting in it. I have tried lots of approaches, but none of them work. So the following has no "counting" in it, just a comment at which point in the code I believe the counter needs to be incremented.
#
# euler 024 : Lexicographic permutations
#
import time
startTime= time.time()
#
def splitList(listStem,listTail):
for idx in range(0,len(listTail)):
tempStem =((listStem) + (listTail[idx],))
tempTail = ((listTail[:idx]) + (listTail[1+idx:]))
splitList(tempStem,tempTail)
if len(listTail) ==0:
#
# I want to increment counter only when I am here
#
print("listStem=",listStem,"listTail=",listTail)
#
inStem = ()
#inTail = ("0","1","2","3","4","5","6","7","8","9")
inTail = ("0","1","2","3")
testStem = ("0","1")
testTail = ("2","3","4","5")
splitList(inStem,inTail)
#
print('Code execution duration : ',time.time() - startTime,' seconds')
Thanks in advance,
Clive
Since it seems you've understood the basic problem but just want to understand how the recursion is happening, all you need to do is pass a variable that tells you at what point of the call stack you're in. You can add a 3rd argument to your function, and increment it with each recursive call:
def splitList(listStem, listTail, count):
for idx in range(0,len(listTail)):
...
splitList(tempStem, tempTail, count)
if len(listTail) == 0:
count[0] += 1
print('Count:', count)
...
Now, call this function like this (same as before):
splitList(inStem, inTail, [0])
Why don't you write generator for this?
Then you can just stop on nth item ("drop while i < n").
Mine solution is using itertools, but you can use your own permutations generator. Just yield next sequence member instead of printing it.
from itertools import permutations as perm, dropwhile as dw
print(''.join(dw(
lambda x: x[0]<1000000,
enumerate(perm('0123456789'),1)
).__next__()[1]))

repetitive value assignment in a while loop, Python

Please look at following while loop code written in Python:
x=25
epsilon=0.01
high=max(1.0,x)
low=0.0
*ans=(low+high)/2.0*
while abs(ans**2-x)>=epsilon:
if ans2>x:
high=ans
else:
low=ans
*ans = (high + low)/2.0*
print("ans:",ans,)
This is a guess loop (exhaustion), it should find the approx for square root of a positive number within the margin error on 0,01.
But I cant understand why we must define ans (ans=(low+high)/2.0) the second time, first before the loop and then again in the loop. Could someone tell me what purpose the second definition have since im seeing the first one being enough?
Thanks
Arif
It's because you need to perform that calculation on each iteration of the loop including the very first iteration. Since your while test is the very first part of the loop, you need to do it once before the loop starts.
Here's a way to do it with just one statement:
while True:
*ans = (high + low)/2.0*
if abs(ans**2-x)>=epsilon:
break
if ans2>x:
high=ans
else:
low=ans

Saving results from for loop and incrementing the index

I am new to Python and I'm writing a program to compute the resultants of distributed forces.
My method works like this:
force =[1,2,3,4,5]
distance =[2,3,4,5,6]
The idea is to break any section of a distributed force into 2 triangles whose area can be found using:
lowerarea = ((distance[i+1] - distance[i]) *force[i]) * 0.5
upperarea = ((distance[i+1] - distance[i]) *force[i+1]) * 0.5
This is my for loop to find the lower areas:
for i in range(0,len(force)):
lowerarea= (dist[i+1]-dist[i])*force[i]*0.5
print (f)
i = i+1
I obviously get the error that the index is out of bounds since d[6] doesn't exist how do i stop the loop once d[5] is evaluated?
Also how do i save the output of the loop f to a new variable?
Thanks!
The problem with the index going out of bounds is because you're doing an additional increment with i = i+1. Remove that line, because the loop is already doing that increment for you. By having it in there, you're pushing the value of i beyond len(force) - 1 (which as the other folks already pointed out is the highest index of these arrays).
As to f, you're not using or changing it at all during the loop, so why print it or try to store its value? The value isn't going to change anywhere in this code.
Why not create a new list?
results = []
for (...):
results.append(f)
Your out-of-range error is due to the fact that len(force) == 6 -- you want len(force) - 1.

Project Euler #82 (Python)

First of all this is the problem : https://projecteuler.net/problem=82 .
This is my code :
# https://projecteuler.net/problem=82
matrice = open('matrix3.txt','r').read().split('\n')
m = []
for el in matrice:
if el=='':
continue
tmp = el.split(',')
m.append(tmp)
matrix = [[0 for i in range(80)]for j in range(80)]
x,y = 0,0
while(True):
matrix[x][y]=int(m[x][y])
y+=1
if y==80:
y=0
x+=1
if x==80:
break
tmp = [0]*80
x,y = 0,78
while(True):
if x==0:
tmp[x]=min(matrix[x][y+1],matrix[x+1][y]+matrix[x+1][y+1])
if x==79:
tmp[x]=min(matrix[x][y+1],matrix[x-1][y]+matrix[x-1][y+1])
else:
tmp[x]=min(matrix[x][y+1],matrix[x-1][y]+matrix[x-1][y+1],matrix[x+1][y]+matrix[x+1][y+1])
x+=1
if x==80:
for e in range(80):
matrix[e][y]+=tmp[e]
tmp = [0]*80
x=0
y+=-1
if y<0:
break
minimo = 10**9
for e in range(80):
if matrix[e][0]<minimo:
minimo=matrix[e][0]
print(minimo)
The idea behind this code is the following:
I start from the 79th column(78th if you start counting from 0) and I calculate the best(the minimal) way to get from any given entry in that column to the column to the right.
When the column is over I replace it with the minimal results I found and I start doing the same with the column to the left.
Is anyone able to help me understand why I get the wrong answer?(I get 262716)
The same code works for the matrix in the example(It works if you change the indeces of course).
If I understand the question, your code, and your algorithm correctly, it looks like you aren't actually calculating the best way to get from one column to the next because you're only considering a couple of the possible ways to get to the next column. For example, consider the first iteration (when y=78). Then I think what you want is tmp[0] to hold the minimum sum for getting from matrix[0][78] to anywhere in the 79th column, but you only consider two possibilities: go right, or go down and then go right. What if the best way to get from matrix[0][78] to the next column is to go down 6 entries and then go right? Your code will never consider that possibility.
Your code probably works on the small example because it so happens that the minimum path only goes up or down a single time in each column. But I think that's a coincidence (also possibly a poorly chosen example).
One way to solve this problem is using the following approach. When the input is a NxN matrix, define a NxN array min_path. We're going to want to fill in min_path so that min_path[x][y] is the minimum path sum starting in any entry in the first column of the input matrix and ending at [x][y]. We fill in one column of min_path at a time, starting at the leftmost column. To compute min_path[i][j], we look at all entries in the (j-1)th column of min_path, and the cost of getting from each of those entries to (i, j). Here is some Python code showing this solution: https://gist.github.com/estark37/5216851. This is an O(N^4) solution but it can probably be made faster! (maybe by precomputing the results of the sum_to calls?)

Categories

Resources