Printing numbers from a loop on a line python - python-2.7

Using
for i in range(5):
print i+1,
it prints 1 2 3 4 5
Is there anyway for it to print without any spaces e.g. 12345

The key is to create a single string that gets printed once. You can do
print ''.join(map(str, range(1,6)))
or
print ''.join(str(i+1) for i in range(5))
Or use the Python 3 compatible print function which takes an end argument.
from __future__ import print_function
for i in range(5):
print(i+1, end='')
The print function also takes a sep argument so you can print your entire range in one go.
from __future__ import print_function
print(*range(1,6), sep='')

>>> s=''
>>> for i in range(5):
... s=s+str(i+1)
...
>>> s
'12345'

Related

append multiple numbers into a list

I have this column of numbers from a txt file that I want to append into a list:
18.0
13.0
10.0
12.0
8.0
my code for placing all these numbers into a list is
last_number_lis = []
for numbers_to_put_in in (path/to/txt):
last_number_lis.append(float(last_number))
print last_number_lis
I want the list to look like
[18.0,13.0,10.0,12.0,8.0]
but instead, when running the code, it shows
[18.0]
[13.0]
[10.0]
[12.0]
[8.0]
Is there any way that all the number can be in one line. Later on, I would like to add all the numbers up. Thanks for your help!!
you can append a list just like :
>>> list=[]
>>> list.append(18.0)
>>> list.append(13.0)
>>> list.append(10.0)
>>> list
[18.0, 13.0, 10.0]
but depend where your number are coming from ...
for example with input in terminal :
>>> list=[]
>>> t=input("type a number to append the list : ")
type a number to append the list : 12.45
>>> list.append(float(t))
>>> t=input("type a number to append the list : ")
type a number to append the list : 15.098
>>> list.append(float(t))
>>> list
[12.45, 15.098]
or reading from file :
>>> list=[]
>>> with open('test.txt', 'r') as infile:
... for i in infile:
... list.append(float(i))
...
>>> list
[13.189, 18.8, 15.156, 11.0]
If it is from a .txt file you would have to do the readline() method,
You could do a for loop and loop through the list of numbers (you never know how many numbers you may be given and might as well let the loop handle it,
with open(file_name) as f:
elemts = f.readlines()
elemts = [x.strip() for x in content]
and then you'd want to loop through the file and add the elements in the list
last_number_list = []
for last_number in elements:
last_number_list.append(float(last_number))
print last_number_list
A slightly less compact but easy to read approach is
num_list = []
f = open('file.txt', 'r') # open in read mode 'r'
lines = f.readlines() # read all lines in file
f.close() # safe to close file now
for line in lines:
num_list.append(float(line.strip()))
print num_list

pymongo float precision

I have a number stored in mongo as 15000.245263 with 6 numbers after decimal point but when I use pymongo to get this number I got 15000.24. Is the pymongo reduced the precision of float?
I can't reproduce this. In Python 2.7.13 on my Mac:
>>> from pymongo import MongoClient
>>> c = MongoClient().my_db.my_collection
>>> c.delete_many({}) # Delete all documents
>>> c.insert_one({'x': 15000.245263})
>>> c.find_one()
{u'x': 15000.245263, u'_id': ObjectId('59525d32a08bff0800cc72bd')}
The retrieved value of "x" is printed the same as it was when I entered it.
This could happen if you trying to print out a long float value, and i think it is not related to mongodb.
>>> print 1111.1111
1111.1111
>>> print 1111111111.111
1111111111.11
>>> print 1111111.11111111111
1111111.11111
# for a timestamp
>>> import time
>>> now = time.time()
>>> print now
1527160240.06
For python2.7.10 it will just display 13 character(for my machine), if you want to display the whole value, use a format instead, like this:
>>> print '%.6f' % 111111111.111111
111111111.111111
And this is just a display problem, the value of the variable will not be affected.
>>> test = 111111111.111111 * 2
>>> test
222222222.222222
>>> print test
222222222.222

How to change parameters without stopping the program

Suppose I write a program like this.
# run the program until the user gives a "stop" input
usrinpt=""`
n=1
while usrinpt!="stop":
n+=1
---- do-something -----
---- do-something -----
---- do-something -----
print n # print the number of loops it has gone through.
Now program will run until I manually change the parameter usrinpt to "stop". But using raw_input will stop the simulation at every step which is not what I want.
So, is there a way to change the usrinpt without stopting the simulation?
A more involved solution using a thread:
from __future__ import print_function # Python 2/3 compatibility
import sys
from time import sleep
from threading import Thread
if sys.version_info.major < 3:
input = raw_input
def do_something():
# doing the work
sleep(1)
usrinpt = ''
def main():
n = 1
while usrinpt != 'stop':
n += 1
do_something()
print('\nnumber of loops', n)
thread = Thread(target=main)
thread.start()
while True:
print('Enter "stop" to terminate program')
usrinpt = input().strip().lower()
if usrinpt == 'stop':
break
thread.join()
Sample program run:
python stop.py
Enter "stop" to terminate program
hello
Enter "stop" to terminate program
stop
number of loops 6
You can catch a KeyboardInterrupt exception:
from __future__ import print_function # Python 2/3 compatibility
n = 1
try:
while True:
n += 1
except KeyboardInterrupt:
print('\nnumber of loops', n)
When the user types <CTRL>-<C> the program prints the number of iterations and continues.

Python isnan - TypeError: Not implemented for this type

I have a list like this:
- 1 21 84.0104
- 2 22 81.9372
- 3 23 NaN
- 4 00 NaN
- 5 01 78.7023
- 6 02 80.0526
In my code I tried to replace all NaN's with zero. So I used Numpy isnan:
import pylab as pl
import numpy as np
from numpy import isnan
filename = "dataset"
file = open(filename)
data = []
for line in file:
data.append(line.strip('\n').strip('\t').split(' '))
NaNs = np.isnan(data)
data[NaNs] = 0
But this doesn't work for me and I get the Error-Message:
"NaNs = np.isnan(data)
TypeError: Not implemented for this type"
I also tried to integrate the module pandas with:
import pandas as pd
But this doesn't work for me either. I only get an "ImportError: No module named pandas". Can anybody help me to understand and solve this problem? Thanks!
If the data coming in is a string, which it looks like it is, you could probably just use:
line.replace("NaN", "0")
This should replace all NaN with a 0.

Python - The integer linear programming (ILP) function in CVXOPT is not generating correct results

I'm trying to solve the simple example found in https://en.wikipedia.org/wiki/Integer_programming#Example using the CVXOPT library on Python 2.7 ; The optimal answers are either (1,2) or (2,2). I'm getting (0.0 , 0.0). What am I doing wrong in the code below ? Thanks !
import numpy as np
import cvxopt
from cvxopt import glpk
c=cvxopt.matrix([0,-1]) #-1 since we're maximising the 2nd variable
G=cvxopt.matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=cvxopt.matrix([1,12,12,0,0],tc='d')
(status, x)=glpk.ilp(c,G.T,h,B=set([0,1]))
print status
print x[0],x[1] #should be (1,2) or (2,2)
print sum(c.T*x)
Your code is basically correct but needs two minor modifications:
The c-vector must be a double, too.
The variables x[0] and x[1] are supposed to be integer, not binary.
Then, a working solution is given by:
import numpy as np
import cvxopt
c=cvxopt.matrix([0,-1],tc='d')
G=cvxopt.matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=cvxopt.matrix([1,12,12,0,0],tc='d')
(status, x)=cvxopt.glpk.ilp(c,G.T,h,I=set([0,1]))
print status
print x[0],x[1]
print sum(c.T*x)
Update for Python 3.8.8
from cvxopt.glpk import ilp
import numpy as np
from cvxopt import matrix
c=matrix([0,-1],tc='d')
G=matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=matrix([1,12,12,0,0],tc='d')
(status, x)=ilp(c,G.T,h,I=set([0,1]))
print (status)
print (x[0],x[1])
print (sum(c.T*x))
Calling:
cvxopt.glpk.ilp(c,G.T,h,I=set([0,1]))
returns:
module 'cvxopt' has no attribute 'glpk'