Python 2.7 for loop confusion - python-2.7

I'm trying to build a table from user input to export via Cheetah to fill a template to use as a report. I'm having trouble separating each iteration of the loop
"for j in range(1, numErrors):" and put table row tags at the beginning and end of each concatenation.
table = ""
cells = ""
row = ""
numMeas = int(raw_input("Enter total number of measurements: "))
numMeas = numMeas + 1 #number of measurements compensated for iteration behavior
for i in range(1, numMeas):
typeMeas = raw_input("Enter type of measurement "+str(i)+": ")
numErrors = int(raw_input("Enter number of error sources: "))
numErrors = numErrors + 1
for j in range(1, numErrors): #builds dataSet from number of errors
inputData = []
inputData.append(typeMeas)
description = raw_input("Enter source of uncertainty "+str(j)+": ")
inputData.append(description)
estUncert = raw_input("Enter estimated uncertainty "+str(j)+": ")
estUncert = float(estUncert)
inputData.append(str(estUncert))
for i in inputData:
cell = "<td>"+str(i)+"</td>"
cells += cell
table = "<tr>"+cells+"</tr>"+"\n"
print table
Current output:
<tr><td>mass</td><td>scale</td><td>1.0</td><td>mass</td><td>human</td><td>2.0</td> <td>temp</td><td>room</td><td>3.0</td><td>temp</td><td>therm</td><td>4.0</td></tr>
Desired output:
<tr><td>mass</td><td>scale</td><td>1.0</td></tr>
<tr><td>mass</td><td>human</td><td>2.0</td></tr>
<tr><td>temp</td><td>room</td><td>3.0</td></tr>
<tr><td>temp</td><td>therm</td><td>4.0</td></tr>

I am guessing it probably needs to look like this:
table = ""
cells = ""
row = ""
numMeas = int(raw_input("Enter total number of measurements: "))
numMeas = numMeas + 1 #number of measurements compensated for iteration behavior
for i in range(1, numMeas):
typeMeas = raw_input("Enter type of measurement "+str(i)+": ")
numErrors = int(raw_input("Enter number of error sources: "))
numErrors = numErrors + 1
inputData = []
for j in range(1, numErrors): #builds dataSet from number of errors
inputData.append(typeMeas)
description = raw_input("Enter source of uncertainty "+str(j)+": ")
inputData.append(description)
estUncert = raw_input("Enter estimated uncertainty "+str(j)+": ")
estUncert = float(estUncert)
inputData.append(str(estUncert))
cells = ''
for i in inputData:
cell = "<td>"+str(i)+"</td>"
cells += cell
table += "<tr>"+cells+"</tr>"+"\n"
print table

Related

Counting rows per record

I'm trying count the total number of invoices where record is concurent.
I am unsure about what it is you exactly want. I'm going to base my expectations on your code.
There are a three errors in the code:
Function arguments should a variable name.
def count_consecutive_invoice (df, invoiceNumber):
retlist = []
for i in range(len(df[InvoiceNumber]) - 1):
Notice the removal of quotes around invoiceNumber. You set, what it's equal to later, when calling the function.
You are trying to call the function instead of accessing a variable:
if count_consecutive_invoice[i] + 1 == count_consecutive_invoice[i
+ 1]:
Should be
if df[InvoiceNumber][i] + 1 == df[InvoiceNumber][i + 1]:
You need to declare all variables, including count.
To do this, just add count = 1 after retlist = [].
This code should work:
df = pd.read_excel(r'MYPath\Book1.xlsx')
def count_consecutive_invoice (df, invoiceNumber):
retlist = []
count = 1
for i in range(len(df[ivoiceNumber]) - 1):
# Check if the next number is consecutive
if df[invoiceNumber][i] + 1 == df[invoiceNumber][i+1]:
count += 1
elif count > 1:
# If it is not and count > 1 append the count and restart counting
retlist.append(count)
count = 1
# Since we stopped the loop one early append the last count
retlist.append(count)
return retlist
output = count_consecutive_invoice(df, 'Invoice Number')
print(output)
output:
[4]
Here is my commented solution.
It does recreate a panda frame, you need to pass the rows name for the id and the one on which we count the invoicing.
def count_consecutive_invoice(table, invoice_row_name, id_row_name):
invoiced_table = {} # the output
for row in table:
if row != invoice_row_name:
invoiced_table[row] = []
invoiced_table['Cont of Consecutive Invoices'] = []
streak = False # keep track of streaking invoices cause on first invoice we need to add 2, not 1
for line in range(len(table[invoice_row_name]) - 1):
id = table[id_row_name][line]
if not id in invoiced_table[id_row_name]:
for row in table:
if row != invoice_row_name:
invoiced_table[row].append(table[row][line])
invoiced_table['Cont of Consecutive Invoices'].append(0)
if id == table[id_row_name][line+1]: #check the vendor id so if you get the invoicing for each
if table[invoice_row_name][line]+1 == table[invoice_row_name][line+1]: # check the actual invoicing
itable_line = invoiced_table[id_row_name].index(id)
invoiced_table['Cont of Consecutive Invoices'][itable_line] += 1 + int(not streak) #otherwise we add 1 or 2 depending on the streak status
streak = True
continue
streak = False
return invoiced_table
invoiced = count_consecutive_invoice(df, "Invoice ID", "Vendor ID")
print(pd.DataFrame.from_dict(invoiced))

can't add everything together? (stuck on the last code)

*ignore this part, just look at the last few codes. im trying to add all the quanties together but the last code prints every purchase individually? How can i get it to print "Your purchases is" and add the quanties times their price all in one line instead of printing it for every individual
print "Enter a fruit name (or done):",
fruit = raw_input()
fruit_list = []
while fruit != "done":
fruit_list = fruit_list + [fruit]
print "Enter a fruit name (or done):",
fruit = raw_input()
price_list = []
for x in range(0, len(fruit_list)):
print "Enter the price for " + fruit_list[x] + ":",
price = float(raw_input())
price_list = price_list + [price]
# print " Your fruit list is:" + str(fruit_list)
# print "Your price list is:" + str(price_list)
print fruit_list
print price_list
quanity_list = []
for x in range(0, len(fruit_list)):
print str(fruit_list[x]) + str(price_list[x]) + " Quantity:",
quantity = int(raw_input())
print "Your total purchase is:", + price_list[x] * quantity
Try the following code :
Replace your last part of code with;
total = 0
quanity_list = []
for x in range(0, len(fruit_list)):
print str(fruit_list[x]) + str(price_list[x]) + " Quantity:",
quantity = int(raw_input())
total = total + price_list[x] * quantity
print "Your total purchase is:" + total

Please point out my mistake in the following program

Here m trying to extract a list of blacklist IP from a specific site and trying to make an excel sheet of the following fields :
IP , date ...... New updated code is :
import xlwt
import urllib
def Bl():
link = 'https://www.dshield.org/ipsascii.html?limit=100'
p = urllib.urlopen(link)
text = p.readlines()
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('python')
sheet.write(0,0,'Blacklist IP')
sheet.write(0,1,'Reports')
sheet.write(0,2,'abcd')
sheet.write(0,3,'date')
sheet.write(0,4,'Date')
row = 1 #counter for rows.
col = 0 #counter for columns.
x = 0 #counter for printing the n'th element in the string w.
for line in text:
li = line.strip()
w = line.split()
if not li.startswith("#"):
sheet.write(row,col,w[0])
sheet.write(row,1,w[1])
sheet.write(row,2,w[2])
sheet.write(row,3,w[3])
sheet.write(row,4,w[4])
row = row + 1
wbk.save('new.xls')
Bl()
I believe it should be this, though my python isn't great:
import xlwt
import urllib
link = 'https://www.dshield.org/ipsascii.html?limit=100'
p = urllib.urlopen(link)
text = p.readlines()
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('Blacklist IP')
row = 1 #counter for rows.
col = 0 #counter for columns.
#x = 0 #counter for printing the n'th element in the string w.
for line in text:
li = line.strip()
w = line.split()
print "The line " + line + " was split into " + len(w) + " size"
for i in range(0,len(w)-1):
if not li.startswith("#") and not li.isspace():
sheet.write(row,col,w[i])
#x = x + 1
col = col + 1
if col > 256:
print "Line of " + li
print "Row: " + row
print "Col: " + col
raise ValueError('Too many columns, can\'t insert ' + w)
row = row + 1
wbk.save('new.xls')
Reasoning is that I believe you should be changing column every time you write a value, since that appears to be causing your current error. I also believe You should be changing row after each line, not just at the end of the code which then appears superfluous
[Edit update after user feedback]

How to avoid duplicate printing of random choiced names from list ( Python)

This program prints duplicate names generated from list please help me get rid of it I added a operator fr it but it's not working
#Subscriber Selector
import random
print "Welcome to Subscriber Picker"
sub_list = ["Ali Abbas","Ansar Abbasi","Hasan Abidi","Saadia Afzaal","Iqbal Ahmad","Iftikhar Ahmad","Khaled Ahmed","Ahmed Tamim","Maulana Mahboob Alam","Malik Barkat Ali"]
def add_list():
input_1 = int(raw_input("How many new users do you want to add? "))
for z in range (0,input_1):
sub_list.append(raw_input ("Enter Name" +" "+ str(z+1) + ":"))
return
add_list()
def generator():
input_2=int(raw_input("How many subscribers to generate? "))
print "-----"
index=0
temp_list = []
ran_name = random.randint(0, len(sub_list)-1)
temp_list.append(sub_list[ran_name])
while len(temp_list) < input_2:
ran_name=random.randint(0,len(sub_list)-1)
temp_list.append(sub_list[ran_name])
if(temp_list[index] == temp_list[index+1]):
temp_list.pop(index)
else:
index = index + 1
for x in temp_list:
print x
print"-----"
return
generator()
Here you go:
temp_list = random.sample( sub_list, input_2 )

Random walk code in python [2 dimensions]

Please could you help me by figuring out what is the wrong with my code.
I am trying to write a program that generates random walks in two dimensions and that determines statistics about the position of the walker after 500 steps when the number of walks is 1000, the max step size is 0.9, and the separation between the two positions is 0.001.
import math
import random
import time
print "RANDOM WALKS ANALYSIS IN ONE DIMENSION"
NOFW_ = 1000 #The number of walks
NOFS_= 500 #The number of steps in each walk
MSS_ = 0.9 # The maximum step size[m]
SOFP_ = 0.001 # The separation of positions considered equal[m]
print " Number of walks: %3g"% NOFW_
print " Number of steps in each Walk: %3g"% NOFS_
print " Maximum step size: %3g"% MSS_,"m"
print "Separation of positions considered equal: %3g"% SOFP_,"m"
print
print "Please wait while random walks are generated and analyzed..."
print "Date:" + time.ctime()
print
def initialPosition():
return (0.0, 0.0)
def distance(posA, posB):
"""Calculates the distance between two positions posA and posB"""
distance = math.sqrt((posB[0] - posA[0])**2 + (posB[1] - posA[1])**2)
return distance
def printstats(description, numbers):
minimum_value_ = min(numbers)
numbers.sort()
Tenth_percentile = abs(0.10*len(numbers) + 0.5)
Mean_value_ = (1./float(len(numbers))*sum(numbers))
A = 0
for values in numbers:
B = distance(values, Mean_value_)
B = B**2
A = B + A
Standard_deviation = math.sqrt((1./(len(numbers)-1))*A)
Newposition_ = int(0.90*(len(numbers) + 0.5))
Ninetieth_percentile =numbers[Newposition_]
maximum_value_ = max(numbers)
print "Analysis for"""+ description
print "Minimum value: %9.1f" % minimum_value_
print "10th percentile: %7.1f" % Tenth_percentile
print "Mean value: %12.1f" % Mean_value_
print "Standard deviation: %4.1f" % Standard_deviation
print "90th percentile: %7.1f" % Ninetieth_percentile
print "Maximum value: %9.1f" % maximum_value_
list_1 = [minimum_value_, Tenth_percentile, Mean_value_, Standard_deviation, Ninetieth_percentile,maximum_value_]
return list_1
def takeStep(prevPosition, maxStep):
x = random.random()
y = random.random()
minStep = -maxStep
Z = random.random()*2*math.pi
stepsize_ = random.random()*0.9
Stepx= stepsize_*math.cos(Z)
Stepy= stepsize_*math.sin(Z)
New_positionx = prevPosition[0] + Stepx
New_positiony = prevPosition[1] + Stepy
return (New_positionx, New_positiony)
Step_100 = []
Step_500 = []
count_list = []
for walk in range(NOFW_):
Step1 = []
Position = (0.0,0.0)
count = 0
for step in range(NOFS_):
Next_Step_ = takeStep(Position, MSS_)
for word in Step1:
if distance(Next_Step_, word) <= SOFP_:
count +=1
position = Next_Step_
Step1.append(Next_Step_)
Step_100.append(Step1[-1])
Step_500.append(Step1[-1])
count_list.append(count)
Step_100 = printstats("distance from start at step 100 [m]", Step_100)
Step_500 = printstats("distance from start at step 500 [m]", Step_500)
count_list = printstats("times position revisited", count_list)
Your problem is here
Mean_value_ = (1./float(len(numbers))*sum(numbers))
sum() is supposed to get some numbers but your variable numbers is actually containing some tuples of 2 values
You may want to define your own sum function for tuples of 2 numbers, or to sum the first values and second values separately