I have written a program that eliminates the items in a list and outputs the other list.
Program :
r = [5,7,2]
for i in range(10):
if i != r:
print i
It outputs
0
1
2
3
4
5
6
7
8
9
But I want the desired output to be
0
1
3
4
6
8
9
What is the method to do so?
When you do - i !=r its always true, because an int and a list are never equal. You want to use the not in operator -
r = [5,7,2]
for i in range(10):
if i not in r:
print i
From python documentation -
The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s .
You are checking if a integer is not equal to to list .which is right so it prints all the value
What you really wanted to do is check if the value is not available in the list .So you need to use not in operator
r = [5,7,2]
for i in range(10):
if i not in r:
print i
You can try like this,
>>> r = [5, 7, 2]
>>> for ix in [item for item in range(10) if item not in r]:
... print ix
...
0
1
3
4
6
8
9
Using set
>>> r = [5,7,2]
>>> for i in set(range(10))-set(r):
... print(i)
...
0
1
3
4
6
8
9
>>>
Related
I have written a function and its output is returned as a list,
[32,1,4,5,6]
But I want it to return in this manner,
32
1
4
5
6
How do I return the output as above?
Loop through the list and get the result, as:
result = list(range(10)) # your lists values
for i in result:
print(i)
or you can use:
print(*result, sep='\n')
using functions
>>> def func(n):
... for i in range(n):
... yield i
...
>>> for i in func(10):
... print(i)
...
0
1
2
3
4
5
6
7
8
9
>>> def func2(n):
... result = []
... for i in range(n):
... result.append(i)
... return '\n'.join(str(i) for i in result)
...
>>> func2(10)
'0\n1\n2\n3\n4\n5\n6\n7\n8\n9'
>>> x = func2(10)
>>> print(x)
0
1
2
3
4
5
6
7
8
9
my_list = the_function_that_returns_a_list()
for item in my_list:
print(item)
you can add the following code for getting required output
string = ""
for i in result :
string += i +"/n"
This question already has answers here:
Logical operators in Python [duplicate]
(4 answers)
Closed 5 years ago.
I am trying some operations in Python but I am not understanding the underlying concept of it. I tried various combinations which might be bit tough for you but my objective was how it is working internally in Python.Please find the code below:
>>> 2 or 3
2
>>> 3 or 2
3
>>> 3 or 3
3
>>> 3 or -3
3
>>> -3 or 3
-3
>>> 0 or 3
3
>>> 0 or -9
-9
>>> 3 and 4
4
>>> 3 and 6
6
>>> 0 or None
>>> 0 and None
0
>>> None and 0
>>> None or 0
0
>>> 5 and 2
2
>>> -3 and 6
6
>>> 3 and -6
-6
>>> 3 and 0
0
>>> 0 and 0
0
>>> 0 and 0.0
0
>>> 0.0 and 0
0.0
>>> 0.0 or 0
0
>>> 0 or 0.0
0.0
>>> [] or 3
3
>>> 3 or []
3
>>> 0 or []
[]
>>> [] or 0
0
>>> [] and 3
[]
>>> 3 and []
[]
>>> [] or {}
{}
>>> [] and {}
[]
>>> [] and {}
[]
>>> {} or []
[]
>>> {} and []
{}
This is actually very well described in most tutorials; the general rule is: a and b is b if a is true, else it is a; a or b is a if a is true, else it is b. Now, False, None, (), [], {}, '', 0 and 0.0 are all considered false; practically everything else is true.
I believe you are referring to how truth tables work here. See the following link:
https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Boolean_Expressions
Hope it helps.
I think you are expecting and and or to produce a boolean value, that is, True or False. But they don't. or will return the first operand if that evaluates to True; otherwise it will return the second operand. and will return the first operand if that evaluates to False; otherwise it will return the second operand. For the evaluation, the following count as False: zero integers and floats, the empty string, and empty tuples, lists and dicts. Anything else counts as True, including, for example, the string "0".
This is short-circuiting in action:
a and b
a is False -> a immediately returned
a is True, b is False -> b immediately returned
both True -> the last object is returned (b)
a or b
a is True -> a is immediately returned
a is False, b is True -> b is returned
both False -> the last object returned (b)
Now, some values are considered 'falsey', e.g. bool(value) == False, for example:
False itself
the number zero (0, 0.0, 0 + 0j)
empty containers ([], tuple(), "", {}, set())
None
anything else whose __bool__ method returns False
Others are considered 'truthy'.
(yes, I've searched all around for a solution, and, if did I see it, I wasn't able to relate to my issue. I'm new to Python, sorry!)
I've got a work to do, and it says to me:
"User will input X and Y. Show a sequence from 1 to Y, with only X elements each line."
e.g
2 4 as entrance
1 2
3 4
e.g 2 6
1 2
3 4
5 6
Okay... So, I thought on doing this:
line, final = input().split()
line = int(line)
final = int(final)
List = []
i = 0
total = (final // line)
spot = 0
correction = 0
k = 1
if i != final:
List = list(range(1, final + 1, 1))
i += 1
while k != total:
spot = line * k + correction
correction += 1
k += 1
list.insert(List, spot, '\n')
print(*List)
Ok. So I managed to build my List from 1 to the "final" var.
Also managed to find on which spots (therefore, var "spot") my new line would be created. (Had to use a correction var and some math to reach it, but it's 10/10)
So far, so good.
The only problem is this work is supposed to be delivered on URI Online Judge, and it DEMANDS that my result shows like this:
2 10 as entrance
1 2
3 4
5 6
7 8
9 10
And, using the code I just posted, I get this as a result:
1 2
3 4
5 6
7 8
9 10
Thus, it says my code is wrong. I've tried everything to remove those spaces (I think). Using sys won't work since it only prints one argument. Tried using join (but I could have done it wrong, as I'm new anyway)
Well, I've tried pretty much anything. Hope anyone can help me.
Thanks in advance :)
You have built a list that includes each necessary character, including the linefeed. Therefore, you have a list like this:
[1, 2, '\n', 3, 4, '\n'...]
When you unpack arguments to print(), it puts a separator between each argument, defaulting to a space. So, it prints 1, then a space, then 2, then a space, then a linefeed, then a space... And that is why you have a space at the beginning of each line.
Instead of inserting linefeeds into a list, chunk that list with iter and next:
>>> def chunks(x, y):
... i = iter(range(1, y+1))
... for row in range(y//x):
... print(*(next(i) for _ in range(x)))
... t = tuple(i)
... if t:
... print(*t)
...
>>> chunks(2, 6)
1 2
3 4
5 6
>>> chunks(2, 7)
1 2
3 4
5 6
7
The problem with the approach you're using is a result of a space being printed after each "\n" character in the series. While the idea was quite clever, unfortunately, I think this means you will have to take a different approach from inserting the newline character into the list.
Try this approach: (EDITED)
x, y = input().split()
x, y = int(x), int(y)
for i in range(1, y+1):
if i % x == 0 or i == y:
print(i)
else:
print(i, end=" ")
Output for 3 11
1 2 3
4 5 6
7 8 9
10 11
Output for 2 10
1 2
3 4
5 6
7 8
9 10
Use itertools to take from an iterable in chunks:
>>> import itertools
>>> def print_stuff(x,y):
... it = iter(range(1, y + 1))
... chunk = list(itertools.islice(it,X))
... while chunk:
... print(*chunk)
... chunk = list(itertools.islice(it,X))
...
>>> print_stuff(2,4)
1 2
3 4
>>>
And here:
>>> print_stuff(2,10)
1 2
3 4
5 6
7 8
9 10
>>>
I split user input into two string then convert them into int and comapre if y greater than x by 2 because this is minimum for drawing your sequence
Then i make a list from 1 to y
And iterate over it 2 element for each iteration printing them
x,y=input().split()
if int(y)>int(x)+2:
s=range(1,int(y)+1)
for i in range(0,len(s),2):
print(' '.join(str(d) for d in s[i:i+2]))
result:
1 2
3 4
5 6
7 8
9 10
This is a question from HackerRank
You are given two sets A and B.
Your job is to find whether set A is a subset of set B.
If set A is subset of set B print True.
If set A is not a subset of set B print False.
Input Format:
The first line will contain the number of test cases T.
The first line of each test case contains the number of elements in set A.
The second line of each test case contains the space separated elements of set A.
The third line of each test case contains the number of elements in set B.
The fourth line of each test case contains the space separated elements of set B.
Output Format:
Output True or False for each test case on separate lines.
Sample Input:
3
5
1 2 3 5 6
9
9 8 5 6 3 2 1 4 7
1
2
5
3 6 5 4 1
7
1 2 3 5 6 8 9
3
9 8 2
Sample Output:
True
False
False
I coded this and it worked fine. The output and expected output matches but the output is claimed to be wrong. I even checked if it was because of any trailing whitespace characters. Where am I going wrong ?
for i in range(int(raw_input())):
a = int(raw_input()); A = set(raw_input().split())
b = int(raw_input()); B = set(raw_input().split())
if(b<a):
print "False"
else:
print A.issubset(B)
The problem specification says this:
Note: More than 4 lines will result in a score of zero. Blank lines won't be counted.
Your solution uses 7 lines, so it counts as a failure.
In Python-3
##Hackerrank##
##Check Subset##
for i in range(int(input())):
a = int(input())
A = set(input().split())
b = int(input())
B = set(input().split())
print(A <= B)
t = int(input())
ans = []
for i in range(t):
A = int(input())
a = list(map(int,input().split()))
B = int(input())
b = list(map(int,input().split()))
check = 0
for c in range(A):
if(A>B):
check = 0
break
else:
for j in range(B):
if(a[c]==b[j]):
check = 1
break
else:
check = 0
if(check == 0):
break
if(check == 1):
ans.append('True')
else:
ans.append('False')
del a
del b
print('\n'.join(map(str,ans)))
for i in range(int(input())):
a = int(input())
A = set(input().split())
b = int(input())
B = set(input().split())
print(A.issubset(B))
I have this code:
U = [1,2,3,4,5,6,7,8,9,10,11,12]
def bla(anzahl):
zaehlwerk = 0
while zaehlwerk < anzahl:
for x in U:
zaehlwerk = zaehlwerk +1
print x
my query:
bla(3)
I hoped that now I would get the first 3 list items, but instead I get the whole list.
1
2
3
4
5
6
7
8
9
10
11
12
I tried to debug because I thought that maybe the counter wouldn't work, but it does. But then where is my error?
use slicing :
>>> U = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> U[:3]
[1, 2, 3]
U[stat-index:end-index], you will get element from start-index to one less end-index, as in above example
>>>U[2:6]
[3, 4, 5, 6]
what you need to do is this using slicing:
def print_list(n):
print "\n".join(map(str,U[:n]))
print_list(3)
output:
1
2
3
for x in U:
is the innermost loop. That is making sure you iterate over everything.
As is you can modify your code to look like
def bla(anzahl):
zaehlwerk = 0
while zaehlwerk < anzahl:
x = U[zaehlwerk]
zaehlwerk = zaehlwerk +1
print x
And that will work for what you want. But more concise would be to to use something like
for index in range(len(anzahl)):
print U[index]