strings and prints them as columns from list in python - python

I have list of lists of strings like this:
[['today'], ['is'], ['rainy'], ['day']]
I want to print each word vertically in python. I want to output something like this
t i r d
o s a a
d i y
a n
y y

You could try itertools.zip_longest
from itertools import zip_longest
lst = [['today'], ['is'], ['rainy'], ['day']]
print('\n'.join([' '.join([y or ' ' for y in x]) for x in zip_longest(*[i[0] for i in lst])]))
Output:
t i r d
o s a a
d i y
a n
y y

You can do this will a loop.
l = [['today'], ['is'], ['rainy'], ['day']]
max_len = len(max(l, key=lambda x: len(x[0]))[0])
out = ''
for idx in range(max_len):
for item in l:
small_item = item[0]
if len(small_item) > idx:
out += small_item[idx]
out += "\t"
else:
out += " \t"
out += "\n"
print(out)
t i r d
o s a a
d i y
a n
y y
Idea behind this is simple. You have to find the length of longest string you have. Then basically you want to pick up each item from each string if that element is valid, else add a empty space. Add tabs and newlines to format as you want.

lst = [['today'], ['is'], ['rainy'], ['day']]
max_len = len(max(lst, key=lambda x: len(x[0]))[0])
for i in range(max_len):
for word in lst:
try:
print(word[0][i], end=' ')
except IndexError:
print(' ', end=' ')
print()
Output:
t i r d
o s a a
d i y
a n
y y

Related

Combine elements that has same pattern in a list to strings

I have a list of strings that could vary in pattern.
lst = ['ban-eur.kd', 'ban-eur.sd', 'ban-eur.td' ]
When converted this should become ban-eur<kd,sd,td>.
It should combine elements that are next only if they can be combined. (only if it matches the pattern ban-eur)
lst = ['ban-eur.kd', 'kd', 'ban-eur.sd', 'ban-eur.td' ]
This should result in 'ban-eur.kd_kd_ban-eur<sd,td>'.
If it doesn't have any element that could be combined then it should all be just joined with a _
How can I do this, without missing the first element in the array/duplicate with in the string.
Thanks for your time.
You can use itertools.groupby:
import itertools, re
lst = ['ban-eur.kd', 'ban-eur.sd', 'ban-eur.td' ]
def group_result(d:list) -> list:
if len(d) == 1:
return d[0]
new_result = [[a, list(b)] for a, b in itertools.groupby(sorted(d, key=lambda x:x.split('.')[0]), key=lambda x:x.split('.')[0])]
return '_'.join('{}<{}>'.format(a, ','.join(i.split('.')[-1] for i in b)) for a, b in new_result)
new_data = '_'.join(group_result(list(b)) if a else '_'.join(list(b)) for a, b in itertools.groupby(lst, key=lambda x:'.' in x))
Output:
'ban-eur<kd,sd,td>'
When running on ['ban-eur.kd', 'kd', 'ban-eur.sd', 'ban-eur.td']:
'ban-eur.kd_kd_ban-eur<sd,td>'
matches = []
resulting_string
for item in lst:
if item.startsWith('ban-eur'):
matches.append(item)
elif not item.startsWith('ban-eur') and len(matches) >= 1:
if len(matches) == 1:
resulting_string += item
else:
resulting_string += 'ban-eur.<'
for s in matches:
resulting_string += s + ', '
resulting_string += '>'
matches = []
resulting_string += '_' + item + '_'
This should work
pre = ''
result = []
endings = []
for item in lst:
if item.split('.')[0] == pre:
endings.append(item.split('.')[1])
else:
if endings:
result.append(pre+'<'+','.join(endings)+'>')
else:
result.append(item)
pre = item.split('.')[0]
endings = []
print('_'.join(result))

Rhombus shape based on user input

I am trying to create a rhombus made out of letters that a user selects, using Python 3. So if a user selects "B" then the rhombus is
A
B B
A
If the user selects "D" the rhombus would be:
A
B B
C C C
D D D D
C C C
B B
A
Can anyone help me get started on this? As of now, I am thinking if a user selects D then that corresponds to 4 and you would use the equation 2k-1 to determine the size of the "square." I would also create a linked list containing all the letters
so letter = ['A', 'B', 'C', 'D'.... 'Z'] (or would a dictionary be better?)
so:
def rhombus(n):
squareSize = 2n-1
for i in range(1,squareSize):
for l in letter:
print l + "/n"
golfing time \o/
edit: there's of course an SE for code golf and i'll do as in rome
Python 3, 106 bytes
n=26
for x in range(-n, n):
x = abs(x)
print(' '*x+' '.join([chr(64+n-x) for _ in range(n-x)]))
Try it online!
explanation
for x in range(-n, n): generate the rows
' '*x: generate the space before each first letter in the row
chr(64+n-x): display the letter, with chr(65) = "A"
' '.join: join all letters with three spaces between each of them
for _ in range(n-x): will generate the right number of letters. the value itself is useless.
output for n=4:
A
B B
C C C
D D D D
C C C
B B
A
domochevski's answer is great but we don't actually need those imports.
def rhombus(char):
A = 64
Z = A + 26
try:
val = ord(char)
if val < A or val > Z:
return None
except:
return None
L = [ ''.join(([chr(x)]*(x-A))) for x in range(A,val+1) ]
L = [' '.join(list(x)) for x in L]
max_len = max(len(x) for x in L)
L = [x.center(max_len) for x in L]
L += L[-2::-1]
return '\n'.join(L)
print(rhombus('Z'))
Well that was an interesting question. Here is some quick and dirty way to do it:
from string import ascii_uppercase
def rhombus(c): # Where c is the chosen character
# Get the position (1-based)
n = ascii_uppercase.find(c.upper()) + 1
if 0 < n <= 26:
# Get the strings for the top of the rhombus without spaces
l = [ascii_uppercase[i] * ((i)+1) for i in range(n)]
# Add in the spaces
l = [' '.join(list(e)) for e in l]
# Align everything
max_len = max(len(e) for e in l)
l = [e.center(max_len) for e in l]
# Get the bottom from the top
l += l[-2::-1]
# Print the rhombus
for e in l:
print(e)
As I mentioned this is not beautiful code but it should work.

How can I subtract 2 string or list in python?

I have very large strings in my codes. I would like to detect different characters between the strings. Here is an example what I mean:
a='ababaab'
b='abaaaaa'
a=a-b
print(a)
I expect kind of like these; 'bb' or '000b00b'
I know sounds weird but I really need this.
You could do:
a = 'ababaab'
b = 'abaaaaa'
a = ''.join(x if x != y else '0' for x, y in zip(a, b))
# '000b00b'
# OR
a = ''.join(x for x, y in zip(a, b) if x != y)
# 'bb'
Here is the example: It works wih list
listA = ["a","b"]
listB = ["b", "c"]
listC = [item for item in listB if item not in listA]
print listC
Output
# ['c']
You can create custom function as following:
(assumption length of both strings are equal)
def str_substract(str1, str2):
res = ""
for _ in xrange(len(str1)):
if str1[_] != str2[_]:
res += str1[_]
else:
res += "0"
return res
a='ababaab'
b='abaaaaa'
print str_substract(a, b)
output:
000b00b
result = ''
for temp in a:
result += temp if temp not in b else '0'
Use zip:
res = ''
for i, j in zip(a, b):
if i == j:
res += '0'
else:
res += i
Using a list to store the result is probably more efficient.
if you want s1 - s2 :
s1 = 'ababaab'
s2 = 'abaaaaa'
for i,j in zip(s1,s2):
if (i != j):
print i,
output : bb

How to split a string by a list of marks in python?

Suppose we have a sentence like: "ABCDEFG", and a list of marks like: [0,0,1,0,0,0,1]. What I intends to do is split the source string into segments by using the list of marks: if a character has index i in the source string, and by using this index we could get 1 in the list of marks, then this character is the end of a word.
So the source string could be split into ['ABC', 'DEFG']
How to achieve this in Python? I mean, not the simple way like using a temporary buffer.
A simple approach would be:
temp = "ABCDEFG"
t = [0,0,1,0,0,0,1]
f_i, e_i = 0,0
for index,val in enumerate(t):
if val:
e_i = index +1
print temp[f_i: e_i ] #Here you can store these as you wish
f_i = e_i
.index is probably the fastest way to find the 1s. Also allows you to slice the source string directly
s = "ABCDEFG"
L = [0,0,1,0,0,0,1]
pos = 0
res = []
while True:
try:
idx = L.index(1, pos) + 1
except ValueError:
break
res.append(s[pos: idx])
pos = idx
print(res)
We can use simple for loop to acheive this -
>>> s = "ABCDEFG"
>>> l = [0,0,1,0,0,0,1]
>>>
>>> endlist = []
>>> tsh = ''
>>> for i, ch in enumerate(s):
... tsh += ch
... if l[i] == 1:
... endlist.append(tsh)
... tsh = ''
...
>>> endlist
['ABC', 'DEFG']
A simple answer:
l = [0,0,1,0,0,0,1]
s = 'ABCDEFG'
indices = [i for i, x in enumerate(l) if x == 1]
t = 0
a = []
for i in indices:
a.append(s[t:i+1])
t = i+1
print(a)
Another variation on a theme.
marks = [0,0,1,0,0,0,1]
sentence = 'ABCDEFG'
output = []
last_index = 0
for index, mark in enumerate(marks):
if mark:
output.append(sentence[last_index:index+1])
last_index = index+1
print(output)

Insert "X" between identical consecutive letters in a string

Given a string, how can I break it up such that there are no consecutive identical letters, at n, n+1, where n is even.
Meaning, how can i get "abba" to remain "abba", but take "abbb" into "abbXb".
Thanks
Because everyone loves one-liners:
strings = ['ab', 'abba', 'abbb', 'abbba', 'abbababababbbaaaa', 'abcacbbbddbabbdd']
for s in strings:
r = ''.join('X' + v if (k and k % 2 and v == s[k - 1]) else v for (k,v) in enumerate(s))
print s, '->', r
The code reads like this: look at every character in the string. If it's not the first and if it's index is even and it is the same as the character before, prepend an 'X' to the character.
Output:
ab -> ab
abba -> abba
abbb -> abbXb
abbba -> abbXba
abbababababbbaaaa -> abbababababXbbaaXaa
abcacbbbddbabbdd -> abcacbbXbdXdbabXbdXd
Do your own homework, Kevin.
def foo(text, separator):
if len(text) < 2:
return text
result = ""
for i in range(1, len(text), 2):
if text[i] == text[i - 1]:
result += text[i - 1] + separator + text[i]
else:
result += text[i-1:i+1]
if len(text) % 2 != 0:
result += text[-1]
return result
print(foo("ab", "X"))
print(foo("abba", "X"))
print(foo("abbba", "X"))
print(foo("abbababababbbaaaa", "Z"))
Output:
>> ab
>> abba
>> abbXba
>> abbababababZbbaaZaa
You can use itertools.groupby:
from itertools import islice, groupby
import math
def solve(strs, n):
for k, g in groupby(strs):
lis = list(g)
it = iter(lis)
yield 'X'.join(''.join(islice(it, n)) for _ in xrange(int(math.ceil(len(lis)/float(n)))))
Demo:
>>> ''.join(solve("abba", 2))
'abba'
>>> ''.join(solve("abbb", 2))
'abbXb'
>>> ''.join(list(solve('abbbbyyyyy', 2)))
'abbXbbyyXyyXy'
>>> ''.join(solve('abbbbyyyyy', 4))
'abbbbyyyyXy'
May it be good?
from itertools import izip_longest
def X(s):
s_odd = s[::2]
s_even = s[1::2]
output = ''
for o, e in izip_longest(s_odd, s_even):
output += o or ''
if o == e:
output += 'X'
output += e or ''
return output
strings = ['ab', 'abba', 'abbb', 'abbba', 'abbababababbbaaaa', 'abcacbbbddbabbdd']
for s in strings:
print X(s)
result:
ab
abba
abbXb
abbXba
abbababababXbbaaXaa
abcacbbXbdXdbabXbdXd
EDIT
A simpler version:
def X(s):
output = ''
for i in range(0, len(s), 2):
o = s[i]
e = s[i+1] if i < len(s) - 1 else ''
output += o
if o == e:
output += 'X'
output += e
return output
strings = ['ab', 'abba', 'abbb', 'abbba', 'abbababababbbaaaa', 'abcacbbbddbabbdd']
for s in strings:
print X(s)

Categories

Resources