how to choose what value loops first in a while loop [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So i have an array and i want to append certain values to it in a while loop but i want them in a certain order. It's something like this:
num = [1,2,3,4,5]
count = -1
while count < 2:
for x in num:
c.execute('SELECT column FROM table WHERE restriction = %s;', (x + count,))
rows = c.fetchall()
array = []
for row in rows:
array.append(row[0])
count += 1
but i want the values where count = 0 to go first in the array
I know i can just split it up but is there any way to do it in this format and keep it short?
EDIT: Don't worry about the code itself as its just an example and not the code i am using i just want to know if i can loop count = 0 first and then count = -1 and then count = 1 so that in the final array, the results from count = 0 will be first in the list.

I think you are trying to achieve something like this. In the main loop, only store the items in array if count == 0. Otherwise put them into a temporary array. Then after the main loop finishes, move the temporary stuff to the end of the main array. But your code is still a poor solution* and without knowing what you are trying to achieve, this is the best I can provide.
num = [1,2,3,4,5]
count = -1
array = []
tempArray = []
while count < 2:
for x in num:
c.execute('SELECT column FROM table WHERE restriction = %s;', (x + count,))
rows = c.fetchall()
for row in rows:
if count == 0:
array.append(row)
else:
tempArray.append(row)
count += 1
for item in tempArray:
array.append(item)
*I say poor solution because your code is so hard to understand. I am guessing you are trying to do this:
array = []
for x in range(5):
c.execute('SELECT column FROM table WHERE restriction = %s;', (x + 1)
rows = c.fetchall()
for row in rows:
array.append(row)
# now get your remaining data
I think what you really need to do is write a method:
def getRows(x):
c.execute('SELECT column FROM table WHERE restriction = %s;', (x)
rows = c.fetchall()
return rows
for count in range(4):
array.append(getRows(count + 1))
for count in range(4):
array.append(getRows(count))
for count in range(4)
array.append(getRows(count + 2))
which you can then rewrite as:
def getRows(x):
c.execute('SELECT column FROM table WHERE restriction = %s;', (x)
rows = c.fetchall()
return rows
def addToArray(modifier):
for count in range(4)
array.append(getRows(count + modifier))
and then call it 3 times:
addToArray(1)
addToArray(0)
addToArray(2)

Related

Python Csvwriter Randomize Rows

Is it possible to make a randomizer that randomizes entire rows using the csvwriter? The code I have is similar to this:
for i in range(45):
count=count+1
writer.writerow((count,pattern))
Where pattern is a number which corresponds to count. For example: when count=1 pattern=1; count=2 pattern=9; count=3 pattern=17, and so on... I want a way to randomize the rows so that the correct count corresponds to the correct pattern still. Any help is greatly appreciated!
Load it into a two dimensional array storing the count in a[i][0] and the pattern in a[i][1] then shuffle then write them to the csv file.
import random
count = 0
a = []
for i in range(45):
count = count + 1
a.append([count,pattern])
random.shuffle(a)
for i in range(len(a)):
writer.writerow(a[i][0], a[i][1]) #a[i][0] = count, a[i][1] = pattern
This is not really a csvwriter specific question, but the way I understand your question is that you want to write random 'counts' to your csv file, that correspond to a set number. I'm not sure if your pattern in this case is n + 8, but that's how it would look like. One option would be to just create a dictionary with the pattern, select key from the dictionary and then select the value and write them. Like so:
import random
dict = {}
n = 1
for i in range(n):
n += 8
dict[i+1] = n
for i in range(a):
count = random.randint(1,n)
row = (count, dict[count])
writer.writerow(row)

Improve efficiency of python for loop counting items against IDs in nested list

I'm trying to improve the efficiency of a script that takes a nested list representing a data table, with a column of IDs (each of which might have many entries). The script counts the number of IDs that have more than 100 entries, and more than 200 entries.
Is there a way I can not have to cycle through the list each time with the list comprehension maybe?
list_of_IDs = [row[4] for row in massive_nested_list] ### get list of ID numbers
list_of_IDs = set(list_of_IDs) ### remove duplicates
list_of_IDs = list(list_of_IDs)
counter200 = 0
counter100 = 0
for my_ID in list_of_IDs:
temp = [row for row in massive_nested_list if row[4] == my_ID]
if len(temp) > 200:
counter200 += 1
if len(temp) > 100:
counter100 += 1
Use a collections.Counter() instance to count your ids. There is no need to collect all possible ids first. You can then collate counts from there:
from collections import Counter
counts = Counter(row[4] for row in massive_nested_list)
counter100 = counter200 = 0
for id, count in counts.most_common():
if count >= 200:
counter200 += 1
elif count >= 100:
counter100 += 1
else:
break
Given K unique IDs in N nested lists, your code would take O(KN) loops to count everything; worst case (K == N) that means your solution takes quadratic time (for every additional row you need to do N times more work). The above code reduces this no one loop over N items, then another loop over K items, making it a O(N) (linear) algorithm.
The simplest method would be to go:
temp100 = [row for row in massive_nested_list if row[4] == my_ID and row >= 100 and row < 200]
temp200 = [row for row in massive_nested_list if row[4] == my_ID and row >= 200]
then you could go:
len(temp200)
OR
counter200 = len(temp200)

Python, append within a loop

So I need to save the results of a loop and I'm having some difficulty. I want to record my results to a new list, but I get "string index out of range" and other errors. The end goal is to record the products of digits 1-5, 2-6, 3-7 etc, eventually keeping the highest product.
def product_of_digits(number):
d= str(number)
for integer in d:
s = 0
k = []
while s < (len(d)):
j = (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4]))
s += 1
k.append(j)
print(k)
product_of_digits(n)
Similar question some time ago. Hi Chauxvive
This is because you are checking until the last index of d as s and then doing d[s+4] and so on... Instead, you should change your while loop to:
while s < (len(d)-4):

Get n documents in a loop from mongodb

I have a collection of 101 documents, I need to iterate over them taking 10 collections at a time and store a value of a particular field(of 10 documents) in a list.
I tried this:
values = db.find({},{"field":1})
urls = []
count = 0
for value in values:
if(count < 10):
urls.append(value["field"])
count = count + 1
print count
else:
print urls
urls = []
urls.append(value["field"])
count = 1
It doesn't fetch the last value because it doesn't reach if condition. Any elegant way to do this and rectify ths situation?
You reset count to 0 everytime the loop restarted. Move the declaration outside the loop:
count = 0
for value in values:
If urls is already filled, this will be your only problem.
As far as I can tell, you've some data that you want to organize into batches of size 10. If so, perhaps this will help:
N = 10
values = list(db.find({},{"field":1}))
url_batches = [
[v['field'] for v in values[i:i+N]]
for i in xrange(0, len(values), N)
]

Multiplication table in Python [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this problem---
Write code that will print a multiplication table for 10 positive integers across the columns and 10 positive integers down the rows. Prompt the user for the starting values for both the columns and the rows.
My attempt after some explanation from another question, which doesn't print like Id expect it. Where do I call the print statements and what is wrong with the iterations
row = int(raw_input("Enter the first row number: " ))
col = int(raw_input("Enter the frist column number: "))
lastRow = row + 10
lastCol = col + 10
while (row < lastRow):
print "%4d" % (col * row)
while(col < lastCol):
print "%4d" % (col * row),
col += 1
print "%4d" % (col * row)
row += 1
Here's a second go, better but not what I thought get
row = int(raw_input("Enter the first row number: " ))
col = int(raw_input("Enter the frist column number: "))
lastRow = row + 10
lastCol = col + 10
x=row
y=col
while (x < lastRow):
while(y < lastCol):
y += 1
print "%4d" % (y * x)
x += 1
Sorry about the duplicate post, I didn't know that was bad etiquette
(1) Your col variable is not getting reset for each new row.
It is just always incrementing.
Maybe use another pair of variables, like r and c for the iteration itself.
Or store the original row and col in differently-named variables.
(2) Your indentation of the last two lines seems wrong - shouldn't it be inside the first while loop?
(3) You do not need so many print statements.
You should only need one print statement in the inner loop, and another (empty one) to end each line.
Update: Please don't post duplicate questions
Quick edit that does the trick:
row = int(raw_input("Enter the first row number: " ))
col = int(raw_input("Enter the frist column number: "))
lastRow = row + 5
firstCol = col
lastCol = col + 5
while (row < lastRow):
while(col < lastCol):
print "%4d" % (col * row),
col += 1
col = firstCol
row += 1
print
Problems in your code:
col kept at lastCol value in the end of first cycle iteration. It should be reset to starting point after each row
Too many unnecessary print's
row increment should be done inside of first while
And a tip: if you get stuck with problems like this, get a piece of paper, put down simple and small starting values: row = 1, col = 1, up to 3's instead of 10's. And reproduce your algorithm by hand, step by step.

Categories

Resources