I have started learning python and using online interpreter for python 2.9-pythontutor
x=5,6
if x==5:
print "5"
else:
print "not"
It goes in else loop and print not.
why is that?
what exactly x=5,6 means?
, is tuple expr, where x,y will return a tuple (x,y)
so expression 5,6 will return a tuple (5,6)
x is nether 5 nor 6 but a tuple
When you declared x = 5, 6 you made it a tuple. Then later when you do x == 5 this translates to (5, 6) == 5 which is not true, so the else branch is run.
If instead you did x[0] == 5 that would be true, and print 5. Because we are accessing the 0 index of the tuple, which is equal to 5. Check out some tutorials on tuples for more info.
In Python when you write x = 4, 5, it is same as declaring a tuple as x = (4, 5). In interpreter, if you write:
>>> x = 4, 5
>>> x
(4, 5)
Hence, it is similar to comparing a tuple with an int.
X here acts as an array, where x is pointed to the first element of the array as x [0] = 5 and x [1] = 6
Execute this code, and the display will be 5
x=5,6
if x[0]==5:
print "5"
else:
print "not"
and try to See this link "http://www.pythontutor.com/visualize.html#mode=edit " you can run your code python step by step
Related
Im trying to write values to a csv file such that for every two iterations, the result is in the same row and then the next the values print to a new row. Any help would be greatly appreciated. Thank you!
This is what I have so far:
import csv
import math
savePath = '/home/dehaoliu/opencv_test/Engineering_drawings_outputs/'
with open(str(savePath) +'outputsTest.csv','w') as f1:
writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
temp = []
for k in range(0,2):
temp = []
for i in range(0,4):
a = 2 +i
b = 3+ i
list = [a,b]
temp.append(list)
writer.writerow(temp)
The result I am getting now is
[2 3][3 4][4 5][5 6]
[2 3][3 4][4 5][5 6]
But I would like to get this (without the brackets) where each number in a row is in a separate column:
2 3 3 4
4 5 5 6
Try the following:
import csv
import math
savePath = '/home/dehaoliu/opencv_test/Engineering_drawings_outputs/'
with open(str(savePath) +'outputsTest.csv','w') as f1:
writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
temp = [2, 3]
for i in range(2):
temp = [x + i for x in temp]
additional = [y+1 for y in temp]
writer.writerow(temp + additional)
temp = additional[:]
This should return:
# 2 3 3 4
# 4 5 5 6
You start with a temporary containing the numbers 2 and 3. Then, you loop from 0 to 2 (excluding). At every iteration, you increment the values of the temporary by the current index and subsequently create an additional list with these new values of your temporary list. Once that's done, you join the two lists together and write the result out to your file. At this point, you can set your temporary list to be equal to the values of the additional list, before moving on to the next iteration.
I hope this helps.
The way you present it you can do it with a simple seed and increment:
import csv
import os
save_path = "/home/dehaoliu/opencv_test/Engineering_drawings_outputs/"
with open(os.path.join(save_path, "outputsTest.csv"), "w") as f:
writer = csv.writer(f, delimiter="\t", lineterminator="\n")
temp = [2, 3, 3, 4] # init seed
increment = len(temp) // 2 # how many pairs we have, used to increase our seed each row
for _ in range(2): # how many rows do you need, any positive integer will do
writer.writerow(temp) # write the current value
temp = [x + increment for x in temp] # add 'increment' to the elements
Resulting in:
2 3 3 4
4 5 5 6
But if your seed is: temp = [2, 3, 3, 4, 4, 5] and you decide to generate 4 rows, it will still adapt:
2 3 3 4 4 5
5 6 6 7 7 8
8 9 9 10 10 11
11 12 12 13 13 14
I have this list: l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] and I would like to iterate on it, printing something like
0: [1,2,3,4]
1: [2,3,4,5]
2: [3,4,5,6]
...
n: [17,18,19,20]
So far I made this code to print 5 elements at a time, but the last iteration prints 3:
for index, item in enumerate(l):
if index == 0 or index == 1 or index == 2:
continue
print index, l[index - 3:index + 2]
How can I solve this?
You're on the right track with your list slices. Here's a tweak to make it easier:
sub_len = 4
for i in range(len(mylist) - sub_len + 1):
print l[i:i + sub_len]
Where sub_len is the desired length of the slices you print.
demo
So, my question is simple. I'm simply struggling with syntax here. I need to read in a set of integers, 3, 11, 2, 4, 4, 5, 6, 10, 8, -12. What I want to do with those integers is place them in a list as I'm reading them. n = n x n array in which these will be presented. so if n = 3, then i will be passed something like this 3 \n 11 2 4 \n 4 5 6 \n 10 8 -12 ( \n symbolizing a new line in input file)
n = int(raw_input().strip())
a = []
for a_i in xrange(n):
value = int(raw_input().strip())
a.append(value)
print(a)
I receive this error from the above code code:
value = int(raw_input().strip())
ValueError: invalid literal for int() with base 10: '11 2 4'
The actual challenge can be found here, https://www.hackerrank.com/challenges/diagonal-difference .
I have already completed this in Java and C++, simply trying to do in Python now but I suck at python. If someone wants to, they don't have too, seeing the proper way to read in an entire line, say " 11 2 4 ", creating a new list out that line, and adding it to an already existing list. So then all I have to do is search said index of list[ desiredInternalList[ ] ].
You can split the string at white space and convert the entries into integers.
This gives you one list:
for a_i in xrange(n):
a.extend([int(x) for x in raw_input().split()])
and this a list of lists:
for a_i in xrange(n):
a.append([int(x) for x in raw_input().split()]):
You get this error because you try to give all inputs in one line. To handle this issue you may use this code
n = int(raw_input().strip())
a = []
while len(a)< n*n:
x=raw_input().strip()
x = map(int,x.split())
a.extend(x)
print(a)
I have no idea if this is a bug or not, but why does this cause an endless loop?
>>> top_ports = [[1], [0.9], [0.8], [0.7], [0.6]]
>>> a = 2
>>> for x in top_ports:
... if a > x[0]:
... top_ports.insert(0,a)
...
x represents the iterated element inside top_ports. But when a > x[0] is true, an element is added to top_ports:
top_ports.insert(0,a)
So because the length of top_ports continuously increases, the for loop never terminates.
You could also check this by being more verbose. Printing x always yields [1] in your example. This is because as the loop continues to execute, a is always being adding, like this:
[2, 2, 2, ... [1], [0.9], [0.8], [0.7], [0.6]]
The for loop is never really able to jump to the next element because the values also move one further element away.
Hope this helps you!
Inside the loop, you are inserting new items inside your list that is currently under looping processing .. you have to change your code to be like the following
>>> result = []
>>> top_ports = [[1], [0.9], [0.8], [0.7], [0.6]]
>>> a = 2
>>> for x in top_ports:
... if a > x[0]:
... result.insert(0,a)
...
Right now I'm working on Python 2.7 and I have a little issue.
I explain I need to get the index of a list that is into another list:
students=[["A","B"],["A","B"]]
for m in students:
if "A" in m and "B" in m:
print m
When I run this code I got this:
['A', 'B']
['A', 'B']
It seems to be right, it iterates over students and print twice ['A', 'B'] because it's repeated...but if I run this code:
for m in students:
if "A" in m and "B" in m:
print students.index(m)
it prints this:
0
0
It seems that it only iterates over the first element, for me the correct output should be like this:
0
1
Could anyone explain me why Python do that, and how to fix it, Thank you
students.index(m) returns the first index, i, where students[i] equals m.
Since students contains the same item twice, 0 is returned both times.
So the loop is iterating over both items in students, but since student[0] == student[1], when m is bound to students[1], students.index(student[1])) still returns 0.
If you simply want to report the current index of the loop, then use enumerate:
students = [["A","B"],["A","B"]]
for i, m in enumerate(students):
if "A" in m and "B" in m:
print i
prints
0
1