How to delete "," at the end of the program python set - python

l = {"John","Evan"}
for i in l:
print(i,end=",")
How to get python to output: jhon,evan not: jhon,evan, ?

You can join strings (https://docs.python.org/3/library/stdtypes.html#str.join) to achieve this result:
print(','.join(l))
Will print: jhon,even.

If you had a list instead of a set, you could iterate by index and then prepend a comma starting with the second element.
l = {"John", "Evan"}
names = list(l)
for idx in range(len(names)):
if idx > 0:
print(",", end="")
print(names[idx], end="")
# John,Evan

Related

how to print a string a certain number of times on a line then move to a new line

I have the list ['a','b','c','d','e','f','g']. I want to print it a certain way like this:
a b c
d e f
g
this is what I've tried:
result = ''
for i in range(len(example)):
result += example[i] + ' '
if len(result) == 3:
print('\n')
print(result)
but with this I continue to get one single line
Iterate over a range of indices and step by 3, creating slices of three elements at a time.
>>> a = ['a','b','c','d','e','f','g']
>>> for i in range(0, len(a), 3):
... print(a[i:i+3])
...
['a', 'b', 'c']
['d', 'e', 'f']
['g']
>>>
To format the data, you could either join the slice with ' ' or expand it out and use the sep argument to print.
>>> for i in range(0, len(a), 3):
... print(' '.join(a[i:i+3]))
...
a b c
d e f
g
>>> for i in range(0, len(a), 3):
... print(*a[i:i+3], sep=' ', end='\n')
...
a b c
d e f
g
>>>
The problem with the example code above is that len(result) will never be 3. result is always increased by a character plus a space, so its length will always be a multiple of 2. While you could adjust the check value to compensate, it will break if the list elements are ever more than 1 character.
Additionally, you don't need to explicitly print a "\n" in Python, as any print statement will automatically end with a new line character unless you pass a parameter to not do that.
The following takes a different approach and will work for any list, printing 3 elements, separated by spaces, and then printing a new line after every third element.
The end parameter of print is what should be added after the other arguments are printed. By default it is "\n", so here I use a space instead.
Once the index counter exceeds the list size, we break out of the loop.
i = 0
while True:
print(example[i], end=' ')
i += 1
if i >= len(example):
break
if i % 3 == 0:
print() # new line
Using enumerate
example = ['a','b','c','d','e','f','g']
max_rows = 3
result = ""
for index, element in enumerate(example):
if (index % max_rows) == 0:
result += "\n"
result += element
print(result)

How can I match element by element of list?

i'm trying to solve the problem of checking the distance between letters by looking at the alphabet. I described it in a dictionary. I gave "l = 10000" so that later I could easily distinguish the correct numerator. I think the idea itself is good, but it gives me the error "if abs (words [text [i] [j]] - words [text [i] [j + 1]] <10):
IndexError: string index out of range "
I will be grateful for every tip.
Code:
words={'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25,}
text = ['XXUXXTYVXWA', 'YTWYVWUTYA', 'PUOMQVMRNOSNVONOQOQMPPMRTVRSVRUNMOUSVUOTTMNRVQX']
l = 0
t = []
for i in range(0,len(text)):
for j in range(0,len(text[i])):
if abs(words[text[i][j]] - words[text[i][j+1]] < 10):
l = l+1
else:
l = 10000
t.append(l)
l = 0
print(t)
The error is raised with the last iteration, when you want to compare the last letter with the letter after the last letter, which doesn't exist. Perhaps start at 1 and compare the current letter with the previous letter like this:
words={'A':0,'B':1,'C':2,'D':3,'E':4,'F':5,'G':6,'H':7,'I':8,'J':9,'K':10,'L':11,'M':12,'N':13,'O':14,'P':15,'Q':16,'R':17,'S':18,'T':19,'U':20,'V':21,'W':22,'X':23,'Y':24,'Z':25,}
text = ['XXUXXTYVXWA', 'YTWYVWUTYA', 'PUOMQVMRNOSNVONOQOQMPPMRTVRSVRUNMOUSVUOTTMNRVQX']
l = 0
t = []
for i in range(0,len(text)):
for j in range(1,len(text[i])):
if abs(words[text[i][j-1]] - words[text[i][j]] < 10):
l = l+1
else:
l = 10000
t.append(l)
l = 0
print(t)
I would recommend using the ord built-in to check distance between letters.
In [1]: ord("i") - ord("g")
Out[1]: 2

Even values from lists into a set

Here is the given assignment + code:
Write a function even_value_set(list1, list2, list3), which receives
three lists containing integer items as arguments. The function
creates and returns a set that contains all items with even value from
all three lists.
def test():
l = [[],[],[]]
for i in range(3):
for j in range(random.randint(7,14)):
l[i].append(random.randint(1,35))
print ("List" + str(i + 1) +":",l[i])
print ("")
s = even_value_set(l[0],l[1],l[2])
print ("Return type:", str(type(s)).replace("<","").replace(">",""))
print ("Set with even values only:", end = "")
print (set(sorted(list(s))))
test()
import random
I tried using .union() and making adding lists into another before turning them into sets, but didn't have any luck.
You can do this in a simply pythonic way. This function can be written as a simple oneliner using comprehension
def even_value_set(list1, list2, list3):
return set([num for num in list1+list2+list3 if num % 2 == 0])
Basically, what we did here is concatenated all lists, fitered even numbers and then made it into a set.
You can union lists (with duplicates) with the + operation.
union_list = list1 + list2 + list3
If you only want the unique values you can call set on this list.
unique_set = set(union_list)
Now you can create a new empty set and iterate over the unqiue_set and add all the even values:
solution = set()
for v in unique_set:
if v%2==0:
solution.add(v)
def even_value_set(*lsts):
s = set()
for lst in lsts:
s |= {x for x in lst if x % 2 == 0}
return s
Also you can use starring
def even_value_set(*lsts):
return set().union(*[{x for x in lst if x % 2 == 0} for lst in lsts])
And solution with concatenation (more memory).
set comprehension is more effective than set()
def even_value_set(l1, l2, l3):
return {x for x in l1+l2+l3 if x % 2 == 0}
You can make the union of lists using +, like list1 + list2. Then just walk through the result list checking if the number is even and adding in another list.
def even_value_set(list):
result = set()
for val in list:
if val%2 == 0:
result.add(val)
return result
def test():
l = [[],[],[]]
for i in range(3):
for j in range(random.randint(7,14)):
l[i].append(random.randint(1,35))
print ("List" + str(i + 1) +":",l[i])
print ("")
uni = l[0] + l[1] + l[2]
s = even_value_set(uni)
print ("Return type:", str(type(s)).replace("<","").replace(">",""))
print ("Set with even values only:", end = "")
print (set(sorted(list(s))))
test()
import random
Is it what you want? I think your question is confusing.

Merge items in list based on condition

I have a list which looks like:
a = ["/n abc", "def", "ghi", "/n jkl", "mno", "/n pqr", "/n stu"]
I want it to look like this:
a = ["abcdefghi", "jklmno" "pqr" "stu"]
Essentially, what I want the code to do is merge items in the list with the item sequentially below until it encounters an element with the substring "/n". It should do this for the entire list and then remove all instances of the substring "/n "
result = [i.strip() for i in ''.join(a).split('/n') if i]
However you should post your attempt first.
Here is my attempt:
res = []
s = ""
for i in l:
if i.startswith("/n"):
if s:
res.append(s)
s = i[3:]
else:
s+=i
if s:
res.append(s)
print(res)
One basic way (without using special methods):
result = []
i = 0
index = 0
while i < len(a):
if a[i][:2] == '\n':
index += 1
result[index] += a[i]
Please correct me if I did something wrong (it's been a long time since I used Python).

How do you make a for loop to always print zero in the beginning, without having a zero element as a first element?

I tried:
mylist=[1,2,3]
for i in mylist:
time=0
time=time+i
print(time, end="")
and got:
123
but I want to get:
0123
Thanks for help :)
One of a number of ways would be to iterate not over your list, but over a new list that includes zero at the beginning, and then your list. Like so:
mylist=[1,2,3]
for i in [0] + mylist:
print(i, end="")
If the input list is not under your control and you neither want to prepend 0 to it nor to build a new concatenated list (e.g. if it is very large), you can use itertools.chain():
import itertools
mylist = [1, 2, 3]
for i in itertools.chain([0], mylist):
pass # Your loop code...
OK, looking at the edited code:
mylist=[1,2,3]
for i in mylist:
time=0
time=time+i
print(time, end="")
Obviously doing time=0 then time=time+i each time through the loop is the same as time=i. So, print(time, end="") is the same as print(i, end=""). So, let's simplify it before trying to fix it:
mylist=[1,2,3]
for i in mylist:
print(i, end="")
Now, how do we get it to print a 0 at the start? Well, there is no 0 to get anywhere in the loop, so it pretty much has to come before the loop:
mylist=[1,2,3]
print(0, end="")
for i in mylist:
print(i, end="")
Since you mentioned if the zero is not the first element, go with:
mylist = [1,2,3]
print(('0' * (1 if mylist[0] else 0)) + ''.join(str(x) for x in mylist))
This gives you a 0 at the start if 0 is not the first element in mylist :)
>>> mylist = [1,2,3]
>>> print(('0' * (1 if mylist[0] else 0)) + ''.join(str(x) for x in mylist))
0123
>>> mylist = [0,1,2,3]
>>> print(('0' * (1 if mylist[0] else 0)) + ''.join(str(x) for x in mylist))
0123
mylist=[1,2,3]
for i in mylist:
time=0
time=time+i
print(time, end="")
Change this to:
mylist = [1, 2, 3]
print('0', end='')
for i in mylist:
print(str(i), end='')

Categories

Resources