I am trying to iterate through a series of intersections, where each iteration is the intersection of a new set of rows. I have code that looks somewhat like the following:
for liness in range(len(NNCatelogue)):
for iii in [iii for iii, y in enumerate(NNCatelogue[iii]) if y in set(NNCatelogue[liness]).intersection(catid)]:
print iii, y
NNCatelogue is essentially a 1268 X 12 matrix, and each new iteration of liness calls a new row. If I simply put in the row number that I want (ie: 0, 1, 2...) then I get the expected output (without the for loop in front). The code that is written above gives the following output:
10 C-18-1064
4 C-18-1122
4 C-18-1122
5 C-18-1122
5 C-18-1122
7 C-18-1122
8 C-18-1122
9 C-18-1122
10 C-18-1122
11 C-18-1122
6 C-18-1122
...
The expected output should be:
0 C-18-1
1 C-18-259
2 C-18-303
3 C-18-304
4 C-18-309
5 C-18-324
6 C-18-335
7 C-18-351
8 C-18-372
9 C-18-373
10 C-18-518
11 C-18-8
Any idea where I might be going wrong? Any help is greatly appreciated!
UPDATE:
I tried a variation of one of the answers, and while it is closer to what I am expecting, it isn't quite there. Here is what I tried:
counter = 0
for row in NNCatelogue:
for value in row:
if value in set(NNCatelogue[counter]).intersection(catid):
print counter, value
counter += 1
The resultant output is:
0 C-18-1
1 C-18-324
2 C-18-351
3 C-18-4
4 C-18-5
5 C-18-6
6 C-18-7
7 C-18-8
8 C-18-9
9 C-18-10
10 C-18-11
11 C-18-12
12 C-18-13
...
So some of the intersections are correct, though it isn't my desired output... Any ideas from here?
You use iii too often. I cannot even imagine what's exactly going on if you execute this code. Just give your variables useful speaking names and your problem is probably solved.
As I understand what you need:
counter = 0
for row in NNCatelogue:
for value in row:
if value in catid:
print counter, value
counter += 1
It appears that the intersection offers a non-numeric sort... Do you get the proper set (just the wrong permutation)?
Related
How do I make a 3x5 grid out of a list containing 15 items/strings?
I have a list containing 15 symbols but it could very well also just be a list such as mylist = list(range(15)), that I want to portray in a grid with 3 rows and columns. How does that work without importing another module?
I've been playing around with the for loop a bit to try and find a way but it's not very intuitive yet so I've been printing long lines of 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 etc I do apologize for this 'dumb' question but I'm an absolute beginner as you can tell and I don't know how to move forward with this simple problem
This is what I was expecting for an output, as I want to slowly work my way up to making a playing field or a tictactoe game but I want to understand portraying grids, lists etc as best as possible first
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
A mxn Grid? There are multiple ways to do it. Print for every n elements.
mylist = list(range(15))
n = 5
chunks = (mylist[i:i+n] for i in range(0, len(mylist), n))
for chunk in chunks:
print(*chunk)
Gives 3x5
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
Method 2
If you want more cosmetic then you can try
Ref
pip install tabulate
Code
mylist = list(range(15))
wrap = [mylist[x:x+5] for x in range(0, len(mylist),5)]
from tabulate import tabulate
print(tabulate(wrap))
Gives #
-- -- -- -- --
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
-- -- -- -- --
I need to formulate an iteration sequence that follows the output pattern below:
0
1
2
3
4
5
6
6
7
8
However my attempts insofar are yielding an output that returns back to iteration, rather than returning to a logical sequencing:
for i in range(10):
if i==7:
i=i-1
print(i)
0
1
2
3
4
5
6
6
8
9
I feel as though I am overlooking something incredibly simple, or something that is an obvious syntactical error?!
**Edit -
Firstly, thanks for taking the time to assist in this issue.
I did try all the following, unfortunately the general principle is not compatible with the program at hand.
So, to elaborate:
from datetime import date, timedelta
sDate=date(2021,7,24)
eDate=date(2016,1, 1)
delta=sDate-eDate
leapCycle=4
for i in range(delta.days):
date=sDate-timedelta(days=i)
year=date.year
month=date.month
day=date.day
leap_year=(year%leapCycle)
if day==28 and month==2 and leap_year==0:
temp=i-1
print(temp,date)
print(i,date)
and this is outputting
...
510 2020-03-01
511 2020-02-29
511 2020-02-28
512 2020-02-28
513 2020-02-27
...
1971 2016-03-01
1972 2016-02-29
1972 2016-02-28
1973 2016-02-28
1974 2016-02-27
...
As you can see, i is 'held' as required however now the date is reiterated (making the 'holding' obsolete). Please also note, that i is being used to cycle through data sets that correspond to the associated iterate number so it is important that i,date,and data do what is needed.
Thanks again
This is simpler
for i in range(9):
if i==7:
temp=i-1
print(temp)
print(i)
Your code is is causing you to over write your i value.
Maybe you could try something like this:
def print_with_condition(limit, condition):
for i in range(limit):
if condition(i):
print(i)
print(i)
print_with_condition(9, lambda x: x == 6)
The above code would produce this result:
0
1
2
3
4
5
6
6
7
8
EDIT 1
If you want a simpler approach:
for i in range(10):
if i != 9:
if i == 6:
print(i)
print(i)
The last number is not taken into account. You need to write for i in range(9)
In your for loop , when i=7 we temporarily make i=6 and print it. But the for loop had run till the i=7 state , hence for the next iteration 'i' will be 8 due to for loop behavior, which explains your output. You can achieve your desired output , by printing i-1 for every iteration from when i=7.
Code:
for i in range(10):
if i>=7:
print(i-1)
else:
print(i)
Output:
0
1
2
3
4
5
6
6
7
8
Just few lines of change in your code (added print inside if block) gives the desired results:
for i in range(9):
if (i == 7):
print (i-1)
print (i)
OR if you still want to iterate until range(10), this is the code:
for i in range(10):
if (i >= 7):
print (i-1)
else:
print (i)
Output:
0
1
2
3
4
5
6
6
7
8
I'm trying to print the row and column numbers at the top and left when printing a matrix. For example, I want this:
test = [[7,7,7,7],[7,7,7,7],[7,7,7,7]]
to be shown as
0 1 2 3
0 7 7 7 7
1 7 7 7 7
2 7 7 7 7
The matrix prints fine with
for x in test:
print(*x)
I just don't know how to format it correctly so as to show the index numbers. I found the answer here before but, sadly, I seem to have lost the URL to the question.
You can use enumerate to provide indices when looping through an iterable:
for idx, x in enumerate(test):
print(idx, *x)
For the first line you could do this (I hope the formatting turns out correct, can't test it I'm currently on the go):
print(" ", *range(len(test)))
When your matrix contains numbers of variable length, you can look into string formatting to print them as fixed-width strings. Here for example :
How do I make a fixed size formatted string in python?
If you can use pandas:
>>> pandas.DataFrame(test)
0 1 2 3
0 7 7 7 7
1 7 7 7 7
2 7 7 7 7
Please close if this is a duplicate, but this answer does not answer my question as I would like to print a list, not elements from a list.
For example, the below does not work:
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(%3s % mylist)
Desired output:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
Basically, if all items in the list are n digits or less, equal spacing would give each item n+1 spots in the printout. Like setw in c++. Assume n is known.
If I have missed a similar SO question, feel free to vote to close.
You can exploit formatting as in the example below. If you really need the square braces then you will have to fiddle a bit
lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
frmt = "{:>3}"*len(lst)
print(frmt.format(*lst))
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
items=range(10)
''.join(f'{x:3}' for x in items)
' 0 1 2 3 4 5 6 7 8 9'
If none of the other answers work, try this code:
output = ''
space = ''
output += str(list[0])
for spacecount in range(spacing):
space += spacecharacter
for listnum in range(1, len(list)):
output += space
output += str(list[listnum])
print(output)
I think this is the best yet, as it allows you to manipulate list as you wish. even numerically.
mylist = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
print(*map(lambda x: str(x)+" ",a))
So I've been digging into some of the challenges at CodeEval during the last couple of days. One of them asks you to print a pretty-looking multiplication table going up to 12*12. While on my computer this solution works properly, the site does not accept it.
Can somebody help me out?
for i in range(1,13):
for j in range(1,13):
if j==1:
print i*j,
elif i>=10 and j==2:
print '{0:3}'.format(i*j),
else:
print '{0:4}'.format(i*j),
print
Here's a description of the challenge:
Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line).
Print out the table in a matrix like fashion, each number formatted to a width of 4
(The numbers are right-aligned and strip out leading/trailing spaces on each line).
I think that following code may pass, according to the given rules. But it's only a guess
as I'm not playing on codeeval.
# python3 code, use from __future__ import print_function if you're using python2
for i in range(1,13):
for j in range(1,13):
print('{:4}'.format(i*j), end="")
print ("")
I guess your problem is that you're having a 5 alignment because you forgot that the print foo,
syntax in python 2 is adding a space. Also they say width of 4, whereas you tried to be smart, and
align accordingly to the size of the value.
edit: here's more details about what's wrong in your code, let's take two lines of your output:
1 2 3 4 5 6 7 8 9 10 11 12
10 20 30 40 50 60 70 80 90 100 110 120
AA␣BBB␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣
so what your code is doing is:
if j==1: print i*j,
outputs the AA␣,
elif i>=10 and j==2:
print '{0:3}'.format(i*j),
outputs the BBB␣ and
else:
print '{0:4}'.format(i*j),
outputs the CCCC␣.
The ␣ is an extra space added by python because of the use of the , at the end of the print, to get that, see that snippet:
>>> def foo():
... print 1234,
... print 1234,
... print
...
>>> foo()
1234 1234
The format '{0:3}' right aligns the integer to the right as expected, but only with a padding of three, whereas the '{0:4}' does it according to the rules. But as you're adding an extra space at the end, it's not working as you're writing it. That's why it's better to use python3's print expression that makes it simpler, using the end keyword.
Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line).
However, the output fails to meet this requirement which is made more visible by timing bars.
1 2 3 4 5 6 7 8 9 10 11 12^N
2 4 6 8 10 12 14 16 18 20 22 24^N
3 6 9 12 15 18 21 24 27 30 33 36^N
||||----||||----||||----||||----||||----||||----||||----
This correct padding for a "width of 4, right-aligned" should look like
1 2 3 4 5 6 7 8 9 10 11 12^N
||||++++||||++++||||++++||||++++||||++++||||++++
And then with "strip out leading/trailing spaces on each line" the correct result is
1 2 3 4 5 6 7 8 9 10 11 12^N
|++++||||++++||||++++||||++++||||++++||||++++
While the current incorrect output, with the timing bars for correct output looks like
1 2 3 4 5 6 7 8 9 10 11 12^N
|++++||||++++||||++++||||++++||||++++||||++++???????????