How can i print on new lines? - python

How can i print my output from this function and each boolean to be on new line.
def is_palindrome(n):
return str(n) == str(n)[::-1]
numbers = list(map(int, input().split(', ')))
palindrome_status = [is_palindrome(n) for n in numbers]
print(palindrome_status)
Output:
[False, True, False, True]
Expecting:
False
True
False
True

The simplest would be print it one by one:
[print(is_palindrome(n)) for n in numbers]
BUT
List comprehesion shouldn't be used with side effect functions, to have it clean you should use normal loop:
for n in numbers:
print(is_palindrome(n))

Convert boolean to string, then insert newlines.
print("\n".join(map(str, palindrome_status)))

There are two options:
Use a for loop to iterate over the elements and then print
for val in palindrome_status:
print(val)
Use the print separator for newlines while unpacking the list
print(*palindrome_status, sep='\n')

This works with Lua sometimes if you do
print( "string1" ..
"string2")
using "..", it tells it to continue as one function, and it will continue with this until it's closed or ended
I'm not a python guy so, Sorry if it doesnt work in python :C

Related

my program prints the list joined instead of adding it's elements

I was requested to write a function called summer which gets a list and returns its sum but only if all the elements in the list are of the same type.
For example if:
summer(['a','b','c'])
the result will be:
abc
if
summer (['True','False','True'])
the result will be:
2
but
if
summer (['a','1','k'])
it will print the elements are not of the same type.
Here's my code:
def summer(lst):
summary=0
for i in range(len(lst)):
if i==0:
summary=lst[0]
else:
summary+=lst[i]
return summary
lst=input("Insert list ")
lst=lst.split(',')
print(summer(lst))
My code just joins everything:
if the input is True, False the printing is TrueFalse
please help me fix it, thank you!
The first thing you'll have to do is to check each element's type.
So over your if/else condition within the for loop, consider to check if all elements are of the same type. Something like:
for item in lst:
if (type(item) != lst[0]):
break;
If I correctly understood your problem, only if there's no difference among all the elements then the desired operation should be performed.
I hope that it can be clarifying.
I think this might be what you are trying to do or somewhat close.
def summer(lst):
summary=0
if all(isinstance(i,int) for i in lst):
return sum(lst)
if all(isinstance(i,str) for i in lst):
return ''.join(lst)
else:
return 'Elements not the same'
summer([True,False,True])
def summer(items):
from functools import reduce
from operator import add
assert isinstance(items, list)
types = {type(item) for item in items}
if len(types) != 1:
raise TypeError("All items must have the same type!")
return reduce(add, items)
Output:
>>> summer(["a", "b", "c"])
'abc'
>>> summer([1, 2, 3])
6
>>> summer([True, False, True])
2
>>> summer([True, False, "A"])
TypeError: All items must have the same type!

Printing lists in python without spaces

I am doing a program that changes a number in base 10 to base 7, so i did this :
num = int(raw_input(""))
mod = int(0)
list = []
while num> 0:
mod = num%7
num = num/7
list.append(mod)
list.reverse()
for i in range (0,len(list)):
print list[i],
But if the number is 210 it prints 4 2 0 how do i get rid of the spaces
You can use join with list comprehension:
>>> l=range(5)
>>> print l
[0, 1, 2, 3, 4]
>>> ''.join(str(i) for i in l)
'01234'
Also, don't use list as a variable name since it is a built-in function.
In python 3 you can do like this :
print(*range(1,int(input())+1), sep='')
Your output will be like this if input = 4 :
1234
Convert the list to a string, and replace the white spaces.
strings = ['hello', 'world']
print strings
>>>['hello', 'world']
print str(strings).replace(" ", "")
>>>['hello','world']
Take a look at sys.stdout. It's a file object, wrapping standard output. As every file it has write method, which takes string, and puts it directly to STDOUT. It also doesn't alter nor add any characters on it's own, so it's handy when you need to fully control your output.
>>> import sys
>>> for n in range(8):
... sys.stdout.write(str(n))
01234567>>>
Note two things
you have to pass string to the function.
you don't get newline after printing.
Also, it's handy to know that the construct you used:
for i in range (0,len(list)):
print list[i],
is equivalent to (frankly a bit more efficient):
for i in list:
print i,
Doing the following worked for me in Python3
print(*list,sep='')
You can use below code snippet for python3
print(*list(range(1, n + 1)), sep='')
* will remove initial and end character like [{}]
sep = '' will remove the spaces between item.
Use list_comprehension.
num= int(raw_input(""))
mod=int(0)
list =[]
while num> 0:
mod=num%7
num=num/7
list.append(mod)
list.reverse()
print ''.join([str(list[i]) for i in range (0,len(list))])
The print() function has an argument to specify the end character which by default is '\n'. Specifying the end character as '' and printing using a loop will do what you are looking for:
n_list = [1,2,3,4,5]
for i in n_list:
print(i, end='')
s = "jay"
list = [ i for i in s ]
It you print list you will get:
['j','a','y']
new_s = "".join(list)
If you print new_s:
"jay"

Most pythonic way to check string contains substring which is also present in list

I have string ,
str='http://facebook.com/something/something/1.php'
And have list ,
l= ['facebook','twitter']
I want to check that the str has atleast any of the keyword from the list. What is the most pythonic way to acheive this?
What I have tried is ,
flag=0
for i in l:
if i in str:
print 'YES'
flag=1
break;
if flag==1:
#process something
Using any and generator expression:
>>> s = 'http://facebook.com/something/something/1.php'
>>> l = ['facebook','twitter']
>>> any(x in s for x in l)
True
Side note: Don't use str as a variable name. It shadows a builtin funciton/type str.
You can use any and a generator expression.
s = 'http://facebook.com/something/something/1.php'
l= ['facebook','twitter']
if any(i in s for i in l):
print('YES')
any(i in s for i in l) will iterate over l and test each element to see if it is a substring of s. If a substring is found then the iteration will halt and it will return True, otherwise it will continue until finished and then return False.
The complimentary method of any is all which will only return True if all are True (i.e. all strings are substrings).
You can use
url = 'http://facebook.com/something/something/1.php'
patterns = ['facebook','twitter']
print('YES' if any(pattern in url for pattern in patterns) else 'False')
Alternative
print('YES' if any(url.find(pattern) > -1 for pattern in patterns) else 'False')
Embrace the regex in it
well this is all about regex for me. Your time invested learning regular expressions will be well rewarded.
import re
str='http://facebook.com/something/something/1.php'
l = ['facebook','twitter']
# create the regex
re_l = '|'.join(l)
if re.search(re_l, str):
print "yes"
# do something
This will be faster than any of the other alternatives and allows you to fine tune things. e.g.
# precompile the regex so it only gets done once
re_l = re.compile('|'.join(ll))
# not faster for one but if you reuse it this is faster.
if re_l.search(str):
print "doing something"
BTW since you are looking at the domain name in this example, you can add the re.IGNORECASE flag easily re.compile('|'.join(ll), re.I)

See if all items in a list = certain string

How would I find if I have a list of a given string, 'hello':
x = ['hello', 'hello', 'hello']
# evaluates to True
x = ['hello', '1']
# evaluates to False
Use the all() function to test if a condition holds True for all elements:
all(el == 'hello' for el in x)
The all() function takes an iterable (something that produces results one by one) and will only return True itself if all those elements are true. The moment it finds anything that is false, it'll return False and not look further.
Here the iterable is a generator expression, one that executes an equality test for each element in the input sequence. The fact that all() stops iterating early if a false value is encountered makes this test very efficient if the test in the contained generator expression is False for any element early on.
Note that if x is empty, then all() returns True as well as it won't find any elements that are false in an empty sequence. You could test for the sequence being non-empty first:
if x and all(el == 'hello' for el in x):
to work around that.
This ought to work:
# First check to make sure 'x' isn't empty, then use the 'all' built-in
if x and all(y=='hello' for y in x):
Nice thing about the all built-in is that it stops on the first item it finds that doesn't meet the condition. This means it is quite efficient with large lists.
Also, if all of the items in the list are strings, then you can use the lower method of a string to match things like `'HellO', 'hELLO', etc.
if x and all(y.lower()=='hello' for y in x):
Yet another way to do what you want (all is the most idiomatic way to do that, as all other answers note), useful in case if you need to check more than once:
s = set(l)
cond = (len(s) == 1) and (item in s)
It helps to avoid O(n) traversal every time you want to check the condition.
Using filter and len is easy.
x = ['hello', 'hello', 'hello']
s = 'hello'
print len(filter(lambda i:i==s, x))==len(x)
Youn can do that using set:
set(x) == {'hello'}

Is there any way to shorten this Python generator expression?

I need to build a generator and I was looking for a way to shorten this for loop into a single line. I tried enumerate but that did not work.
counter=0
for element in string:
if function(element):
counter+=1
yield counter
else:
yield counter
counter=0
for element in string:
counter+=bool(function(element))
yield counter
(Yes, adding Booleans to ints works exactly as if True was 1 and False was 0).
The bool() call is only necessary if function() can have return values other than True, False, 1, and 0.
First, you can transform the string into an iterator over the function return values:
truths = (function(x) for x in string)
Then you can map those to 0s and 1s:
onesandzeroes = (1 if function(x) else 0 for x in string)
And then accumulate them:
running = itertools.accumulate(1 if function(x) else 0 for x in string)
As the docs note, accumulate was added in Python 3.2. If you're using 2.x, you can copy and paste the "Equivalent to" recipe from the docs. (If you're using 3.0-3.1, you can do the same, but really, in that case, just upgrade.)
If you're using Python 3, you can do:
from itertools import accumulate
yield from accumulate(1 if function(x) else 0 for x in string)
Although I'd use Simeon Visser's answer. While this one may be short, it isn't immediately clear what the code does.
You could shorten it to:
counter=0
for element in string:
if function(element):
counter+=1
yield counter

Categories