Exponent disappearing when printing numbers - python-2.7

this is my first post to Stack Overflow. I have used it many times before but this is the first error that I have not found a solution to thus far. I am having a problem with a Python script where when I am changing an element in a list, the item replacing the element in the list drops the scientific notation aspect (i.e. E+08). Here is a snippet of the code and terminal output that is very strange to me. Thanks in advance for all help!
for i in range(0, len(EinsteinCof)):
for j in range(0, len(finalindexing)):
if i == finalindexing[j][0]:
if len(finalindexing[j]) == 3:
EinsteinFinal = float(EinsteinCof[finalindexing[j][0]]) + float(EinsteinCof[finalindexing[j][1]]) + float(EinsteinCof[finalindexing[j][2]])
print str(EinsteinFinal)
EinsteinCof[finalindexing[j][0]] = str(EinsteinFinal)
print str(EinsteinCof[finalindexing[j][0]])
Terminal Output:
4.1079763384e+13
4.1079763384 # <-- Where did e+13 go?
2269472400.0
2269472400.0
3.1777892e+12
3.1777892e+1 # <--where did e+12 go?
9.062911e+11
9.062911e+11

Related

Why won't my list.append() not append despite working in print output

Below is my code for the leet code problem: here
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
tripletsList = []
uniqueNums = set(nums)
uniqueNums = list(nums)
for x in range(len(uniqueNums)):
for y in range(len(uniqueNums)):
for z in range(len(uniqueNums)):
print(uniqueNums[x],uniqueNums[y],uniqueNums[z])
if (uniqueNums[x] + uniqueNums[y] + uniqueNums[z]) == 0:
if [[uniqueNums[x],uniqueNums[y],uniqueNums[z]]] not in tripletsList:
tripletsList.append([uniqueNums[x],uniqueNums[y],uniqueNums[z]])
print(tripletsList)
I realize it isn't the optimal solution but in my print line the output shows the correct combination, yet my final triplets list is not eliminating anything which leads me to believe I am not using the "not in" function of python correctly. Any help is greatly appreciated and I must be missing something that is just trivial
I tried first printing every combination of the unique list (yes tons of overlap), then I tried limiting the triplets that made it pass the == 0 check to only triplets that were not already in the triplets list (failed)

How do I eliminate even numbers from this python code without an infinite loop occurring?

I have tried different ways to try print odd numbers only but its only causing an infinite loop to occur. Could you please assist me?
import sys
i = 1
while i < len(sys.argv):
print sys.argv[i]
i = i + 1
Your question is little bit confusing.
You should be processing all arguments and then decide which one you should print.
import sys
i = 1
while i < len(sys.argv):
number = int(sys.argv[i])
if number % 2 == 1:
print number
i = i + 1
In python, sys.argv contains only one item 'main.py' in index number 0.
So, if you run the program from index 1, you will get nothing as output. If you set it from index 0, you will get 'main.py' printed as output.
If this answer is not satisfactory, please clarify your issue with this code.

Python loop query and issue

I'm new to Python so patience may be required on your behalf :) If this is not the right area for this then please let me know. I'm having trouble with a for loop navigating through a list. The idea here is to print "True" when a consecutive set of numbers are found in the list however it shouldn't print true if the sequence contains less than 3 consecutive iterations.
For example:
Ideally the program would say "You have 3 sequences in your list". In this case it would be (1,2,3), (10,11,12) and (22,23,24). Notice there are 2 other consecutive sets of numbers in the list (7,8) and (15,16) however the program should ignore them because it's less than 3 (as mentioned above). Please find code below however I'm at a slight road block. Appreciate any pointers you may have.
list1=[1,2,3,7,8,10,11,12,15,16,22,23,24]
for i in range(len(list1)-1):
if (list1[i] + 1 == list1[i+1]):
count+=1
if count >=3:
print("True")
else:
continue
continue
print(count)
I'm sure I have read the answer in similar posts but I would like to understand the code I'm missing rather than inserting code that doesn't make sense to me.
Thanks
As the query is to have only unique numbers in the sequences .. so below code will just work fine...
list1=[1,2,3,4,5,6,7,8,9,10]
count=0
i=0
while i < (len(list1)-3):
if list1[i]+1 == list1[i+1]:
if list1[i+1]+1 == list1[i+2]:
print(list1[i], list1[i+1], list1[i+2])
i=i+2
count=count+1
i=i+1
print(count)

list out of range when going through an array checking for duplicates in python 2.7

The goal is simple: there is a file with x numbers separated by ` . If there are dublicates of the number in the file they should be deleted. I decided to solve this by comparing the n member with all others from n to len(array). The code:
#deletes repeated numbers separated by `
questioned=open("key_file.txt",'r+')
numbers=questioned.read()
#print(numbers)
numb=[]
number=[]
for each in numbers:
if each=='`':
number.append(''.join(numb))
numb=[]
else:
numb.append(each)
i,j=0,0
for i in xrange(len(number)): #we don't need to compare last number
for j in xrange(i+1,len(number)-1):#don't need to compare to itself
#print(len(number)," ",i," ",j)
if number[i]==number[j]:
number.pop(j) #tried del number[j]
questioned.close()
However, it seems that I manage to get out of range during the process even though I specified that xrange should go to len(array). My guess is the len(number) is not being continually reassessed leading to the number being out of range because a bunch of numbers got deleted?
Any pointers/tips would be great. Thanks a lot for your time!
Alright, it seems like my fears were correct. In the 2nd loop j manages to go over len(number) which leads to the error...
#deletes repeated numbers separated by `
questioned=open("key_file.txt",'r+')
numbers=questioned.read()
#print(numbers)
numb=[]
number=[]
for each in numbers:
if each=='`':
number.append(''.join(numb))
numb=[]
else:
numb.append(each)
i,j=0,0
def compare(number,i,j):
if number[i]==number[j]:
number.pop(j)
compare(number,i,j)
return number
for i in xrange(len(number)):
for j in xrange(i+1,len(number)-1):
if j>len(number)-1:
break
#print(len(number)," ",i," ",j)
#try:
compare(number,i,j)
#except: print('i,j',i,' ',j,'len ',len(number))
questioned.close()
Works fine without try statement. I am not sure why this happens but it does seem to be the case. If you guys have an explanation that would be great :/

Python: Extracting floats from files in a complex directory tree - Are loops the answer?

I have just started doing my first research project, and I have just begun programming (approximately 2 weeks ago). Excuse me if my questions are naive. I might be using python very inefficiently. I am eager to improve here.
I have experimental data that I want to analyse. My goal is to create a python script that takes the data as input, and that for output gives me graphs, where certain parameters contained in text files (within the experimental data folders) are plotted and fitted to certain equations. This script should be as generalizable as possible so that I can use it for other experiments.
I'm using the Anaconda, Python 2.7, package, which means I have access to various libraries/modules related to science and mathematics.
I am stuck at trying to use For and While loops (for the first time).
The data files are structured like this (I am using regex brackets here):
.../data/B_foo[1-7]/[1-6]/D_foo/E_foo/text.txt
What I want to do is to cycle through all the 7 top directories and each of their 6 subdirectories (named 1,2,3...6). Furthermore, within these 6 subdirectories, a text file can be found (always with the same filename, text.txt), which contain the data I want to access.
The 'text.txt' files is structured something like this:
1 91.146 4.571 0.064 1.393 939.134 14.765
2 88.171 5.760 0.454 0.029 25227.999 137.883
3 88.231 4.919 0.232 0.026 34994.013 247.058
4 ... ... ... ... ... ...
The table continues down. Every other row is empty. I want to extract information from 13 rows starting from the 8th line, and I'm only interested in the 2nd, 3rd and 5th columns. I want to put them into lists 'parameter_a' and 'parameter_b' and 'parameter_c', respectively. I want to do this from each of these 'text.txt' files (of which there is a total of 7*6 = 42), and append them to three large lists (each with a total of 7*6*13 = 546 items when everything is done).
This is my attempt:
First, I made a list, 'list_B_foo', containing the seven different 'B_foo' directories (this part of the script is not shown). Then I made this:
parameter_a = []
parameter_b = []
parameter_c = []
j = 7 # The script starts reading 'text.txt' after the j:th line.
k = 35 # The script stops reading 'text.txt' after the k:th line.
x = 0
while x < 7:
for i in range(1, 7):
path = str(list_B_foo[x]) + '/%s/D_foo/E_foo/text.txt' % i
m = open(path, 'r')
line = m.readlines()
while j < k:
line = line[j]
info = line.split()
print 'info:', info
parameter_a.append(float(info[1]))
parameter_b.append(float(info[2]))
parameter_c.append(float(info[5]))
j = j + 2
x = x + 1
parameter_a_vect = np.array(parameter_a)
parameter_b_vect = np.array(parameter_b)
parameter_c_vect = np.array(parameter_c)
print 'a_vect:', parameter_a_vect
print 'b_vect:', parameter_b_vect
print 'c_vect:', parameter_c_vect
I have tried to fiddle around with indentation without getting it to work (receiving either syntax error or indentation errors). Currently, I get this output:
info: ['1', '90.647', '4.349', '0.252', '0.033', '93067.188', '196.142']
info: ['.']
Traceback (most recent call last):
File "script.py", line 104, in <module>
parameter_a.append(float(info[1]))
IndexError: list index out of range
I don't understand why I get the "list index out of range" message. If anyone knows why this is the case, I would be happy to hear you out.
How do I solve this problem? Is my approach completely wrong?
EDIT: I went for a pure while-loop solution, taking RebelWithoutAPulse and CamJohnson26's suggestions into account. This is how I solved it:
parameter_a=[]
parameter_b=[]
parameter_c=[]
k=35 # The script stops reading 'text.txt' after the k:th line.
x=0
while x < 7:
y=1
while y < 7:
j=7
path1 = str(list_B_foo[x]) + '/%s/pdata/999/dcon2dpeaks.txt' % (y)
m = open(path, 'r')
lines = m.readlines()
while j < k:
line = lines[j]
info = line.split()
parameter_a.append(float(info[1]))
parameter_b.append(float(info[2]))
parameter_c.append(float(info[5]))
j = j+2
y = y+1
x = x+1
Meta: I am not sure If I should give the answer to the person who answered the quickest and who helped me finish my task. Or the person with the answer which I learned most from. I am sure this is a common issue that I can find an answer to by reading the rules or going to Stackexchange Meta. Until I've read up on the recomendations, I will hold off on marking the question as answered by any of you two.
Welcome to stack overflow!
The error is due to name collision that you inadvertenly have created. Note the output before the exception occurs:
info: ['1', '90.647', '4.349', '0.252', '0.033', '93067.188', '196.142']
info: ['.']
Traceback (most recent call last):
...
The line[1] cannot compute - there is no "1"-st element in the list, containing only '.' - in python the lists start with 0 position.
This happens in your nested loop,
while j < k
where you redefine the very line you read previously created:
line = m.readlines()
while j < k:
line = line[j]
info = line.split()
...
So what happens is on first run of the loop, your read the lines of the files into line list, then you take one line from the list, assign it to line again, and continue with the loop. At this point line contains a string.
On the next run reading from line via specified index reads the character from the string on the j-th position and the code malfunctions.
You could fix this with different naming.
P.S. I would suggest using with ... as ... syntax while working with files, it is briefly described here - this is called a context manager and it takes care of opening and closing the files for you.
P.P.S. I would also suggest reading the naming conventions
Looks like you are overwriting the line array with the first line of the file. You call line = m.readlines(), which sets line equal to an array of lines. You then set line = line[j], so now the line variable is no longer an array, it's a string equal to
1 91.146 4.571 0.064 1.393 939.134 14.765
This loop works fine, but the next loop will treat line as an array of chars and take the 4th element, which is just a period, and set it equal to itself. That explains why the info variable only has one element on the second pass through the loop.
To solve this, just use 2 line variables instead of one. Call one lines and the other line.
lines = m.readlines()
while j < k:
line = lines[j]
info = line.split()
May be other errors too but that should get you started.