How to iterate all item at once in python list? - python

let's say i have list
strs = ["dog","racecar","car"]
when I = 0 , then I want
d,r,c
when I = 1, then I want
do,ra,ca
when I = 2, then I want
dog,rac,car
like that
How can i do this ?

First Part
1.
strs = ["dog","racecar","car"]
l = 0
for a in strs:
print(a[:l+1],end=' ')
Output
d r c
Explanation.
First loop through all the strings in the list.
Then print the string only to the l index, I use l+1 because the end is excluded.
Means If you run print('hello'[0:3]) it will give all strings to the index 0 to 2 not 3/
set end=' ' so it will not ends with a new line.
2.
strs = ["dog","racecar","car"]
l = 0
lst = [a[:l+1] for a in strs]
print(*lst) # here *lst is same as print(lst[0],lst[1],...,lst[n])
Output
d r c
Second part
1.
strs = ["dog","racecar","car"]
for l in range(min(len(a) for a in strs)):
for s in strs:
print(s[:l+1],end=' ')
print()
Output
d r c
do ra ca
dog rac car
2.
strs = ["dog","racecar","car"]
for l in range(min(len(a) for a in strs)):
print(*[s[:l+1] for s in strs])
Output
d r c
do ra ca
dog rac car
Explanation for min(len(a) for a in strs)
Here inner comprehension(len(a) for a in strs) generates a list with the value as the length of the string inside the list.
Then min(len(a) for a in strs) returns the lowest number from the above list.
I hope my explanation is clear. If not please ask me in the comments.

First you need to find the minimum length and then loop through each size up to that length.
strs = ["dog","racecar","car"]
for l in range(min(len(w) for w in strs)):
print(",".join(s[:l+1] for s in strs))

strs = ["dog","racecar","car"]
def func(arr,n):
w=""
for i in range(len(arr)):
if n<=len(arr[0])-1:
w+=(arr[i])[0:n]+" "
else:
w+=arr[i]+" "
return w;
print(func(strs,2))
Keep on adding sliced portions of each string via loops,If the value of "l" [the variable you used to refer to the final pos] were to exceed the length of the string, the string would be added as a whole. (at least that's how I would handle that case).

Related

Converting a string to integers and assigning them to variables

Example I have line that is "3 2 11" . I want to split that into 3 so "3" , "2", "11" and the convert them into integers and assign them into individual variables my code so far below:
import sys
for line in sys.stdin:
print(line, end="")
snailHasNotEscaped = True
days = 0
totalMs = 0
mPerWholeDay = N - M
while snailHasNotEscaped:
totalMs += mPerWholeDay
days += 1
if totalMs >= H:
snailHasNotEscaped = False
You can use the map function:
x, y, z = map(int, input().split())
Or if you want to use Fast I/O
from sys import stdin
x, y, z = map(int, stdin.readline().split())
Its a oneliner
output = map(int, input.split())
if no of variable is fixed in output then
x, y, z = output
or
x, y, z = map(int, input.split())
I will assume that you have unknown amount of variables so ill store them on a list.
I will use list comprehension to build the new list:
line = "3 2 11"
lst = line.split()
int_lst = [int(ele) for ele in lst]
print(int_lst)
However you can use for instead:
line = "3 2 11"
lst = line.split()
int_lst = []
for ele in lst:
int_lst.append(int(ele))
print(int_lst)
Try something like this:
numericString = "3 2 111".split() # Define str and split
listOfNumbers = list() # Create a new list
for s in numericString: # Loop the splitted elements
listOfNumbers.append(int(s)) # Convert string to integer and append
print(listOfNumbers) # Print the list
#sean. How it going ? Let me help u :)
Imagine your string is
my_string = "3 2 11"
First you need to split it for each number, like this:
my_string.split()
or
my_string.split(' ') #choose your delimiter (ex: '.', ';', ',')
and than Python will return a list like this
>> [3,2,11]
Now you just need to assign to the variable using the function int():
a = int(my_string.split()[0]) #For the fist index on the list "3"
b = int(my_string.split()[1]) #For the second index on the list "2" ...
c = int(my_string.split()[2]) #For the second index on the list "11"
or
a = int(my_string.split(' ')[0]) #For the fist index on the list "3"
b = int(my_string.split(' ')[1]) #For the second index on the list "2" ...
c = int(my_string.split(' ')[2]) #For the second index on the list "11"
Hello,
reading your description - here is something I would try:
Note: If I have misunderstood something, I would be happy if you/someone pointed it out!
>>> s1="3 2 11" # the string "3 2 11"
>>> s2=s1.split() # same string, but split.
>>> s1
'3 2 11'
>>> s2
['3', '2', '11']
>>> ([int(i) for i in s2]) # use type() with a for loop
[3, 2, 11] # to print out every element in the split str `s2`,
# as the type int.
# we can also,
# access one element in s2,
# and check what type that element is:
# by (for example) assigning it to a variable "element_1"
>>> element_1 = ([int(i) for i in s2])[0]
>>> element_1
3
# Check what type it is:
>>> type(element_1)
<class 'int'>
## A example of using + and *:
>>> a=([int(i) for i in s2])[0]
>>> b=([int(i) for i in s2])[1]
>>> c=([int(i) for i in s2])[2]
>>> a,b,c
(3, 2, 11)
>>> (a*b)+c
17

Python - removing repeated letters in a string

Say I have a string in alphabetical order, based on the amount of times that a letter repeats.
Example: "BBBAADDC".
There are 3 B's, so they go at the start, 2 A's and 2 D's, so the A's go in front of the D's because they are in alphabetical order, and 1 C. Another example would be CCCCAAABBDDAB.
Note that there can be 4 letters in the middle somewhere (i.e. CCCC), as there could be 2 pairs of 2 letters.
However, let's say I can only have n letters in a row. For example, if n = 3 in the second example, then I would have to omit one "C" from the first substring of 4 C's, because there can only be a maximum of 3 of the same letters in a row.
Another example would be the string "CCCDDDAABC"; if n = 2, I would have to remove one C and one D to get the string CCDDAABC
Example input/output:
n=2: Input: AAABBCCCCDE, Output: AABBCCDE
n=4: Input: EEEEEFFFFGGG, Output: EEEEFFFFGGG
n=1: Input: XXYYZZ, Output: XYZ
How can I do this with Python? Thanks in advance!
This is what I have right now, although I'm not sure if it's on the right track. Here, z is the length of the string.
for k in range(z+1):
if final_string[k] == final_string[k+1] == final_string[k+2] == final_string[k+3]:
final_string = final_string.translate({ord(final_string[k]): None})
return final_string
Ok, based on your comment, you're either pre-sorting the string or it doesn't need to be sorted by the function you're trying to create. You can do this more easily with itertools.groupby():
import itertools
def max_seq(text, n=1):
result = []
for k, g in itertools.groupby(text):
result.extend(list(g)[:n])
return ''.join(result)
max_seq('AAABBCCCCDE', 2)
# 'AABBCCDE'
max_seq('EEEEEFFFFGGG', 4)
# 'EEEEFFFFGGG'
max_seq('XXYYZZ')
# 'XYZ'
max_seq('CCCDDDAABC', 2)
# 'CCDDAABC'
In each group g, it's expanded and then sliced until n elements (the [:n] part) so you get each letter at most n times in a row. If the same letter appears elsewhere, it's treated as an independent sequence when counting n in a row.
Edit: Here's a shorter version, which may also perform better for very long strings. And while we're using itertools, this one additionally utilises itertools.chain.from_iterable() to create the flattened list of letters. And since each of these is a generator, it's only evaluated/expanded at the last line:
import itertools
def max_seq(text, n=1):
sequences = (list(g)[:n] for _, g in itertools.groupby(text))
letters = itertools.chain.from_iterable(sequences)
return ''.join(letters)
hello = "hello frrriend"
def replacing() -> str:
global hello
j = 0
for i in hello:
if j == 0:
pass
else:
if i == prev:
hello = hello.replace(i, "")
prev = i
prev = i
j += 1
return hello
replacing()
looks a bit primal but i think it works, thats what i came up with on the go anyways , hope it helps :D
Here's my solution:
def snip_string(string, n):
list_string = list(string)
list_string.sort()
chars = set(string)
for char in chars:
while list_string.count(char) > n:
list_string.remove(char)
return ''.join(list_string)
Calling the function with various values for n gives the following output:
>>> string = "AAAABBBCCCDDD"
>>> snip_string(string, 1)
'ABCD'
>>> snip_string(string, 2)
'AABBCCDD'
>>> snip_string(string, 3)
'AAABBBCCCDDD'
>>>
Edit
Here is the updated version of my solution, which only removes characters if the group of repeated characters exceeds n.
import itertools
def snip_string(string, n):
groups = [list(g) for k, g in itertools.groupby(string)]
string_list = []
for group in groups:
while len(group) > n:
del group[-1]
string_list.extend(group)
return ''.join(string_list)
Output:
>>> string = "DDDAABBBBCCABCDE"
>>> snip_string(string, 3)
'DDDAABBBCCABCDE'
from itertools import groupby
n = 2
def rem(string):
out = "".join(["".join(list(g)[:n]) for _, g in groupby(string)])
print(out)
So this is the entire code for your question.
s = "AABBCCDDEEE"
s2 = "AAAABBBDDDDDDD"
s3 = "CCCCAAABBDDABBB"
s4 = "AAAAAAAA"
z = "AAABBCCCCDE"
With following test:
AABBCCDDEE
AABBDD
CCAABBDDABB
AA
AABBCCDE

Count of sub-strings that contain character X at least once. E.g Input: str = “abcd”, X = ‘b’ Output: 6

This question was asked in an exam but my code (given below) passed just 2 cases out of 7 cases.
Input Format : single line input seperated by comma
Input: str = “abcd,b”
Output: 6
“ab”, “abc”, “abcd”, “b”, “bc” and “bcd” are the required sub-strings.
def slicing(s, k, n):
loop_value = n - k + 1
res = []
for i in range(loop_value):
res.append(s[i: i + k])
return res
x, y = input().split(',')
n = len(x)
res1 = []
for i in range(1, n + 1):
res1 += slicing(x, i, n)
count = 0
for ele in res1:
if y in ele:
count += 1
print(count)
When the target string (ts) is found in the string S, you can compute the number of substrings containing that instance by multiplying the number of characters before the target by the number of characters after the target (plus one on each side).
This will cover all substrings that contain this instance of the target string leaving only the "after" part to analyse further, which you can do recursively.
def countsubs(S,ts):
if ts not in S: return 0 # shorter or no match
before,after = S.split(ts,1) # split on target
result = (len(before)+1)*(len(after)+1) # count for this instance
return result + countsubs(ts[1:]+after,ts) # recurse with right side
print(countsubs("abcd","b")) # 6
This will work for single character and multi-character targets and will run much faster than checking all combinations of substrings one by one.
Here is a simple solution without recursion:
def my_function(s):
l, target = s.split(',')
result = []
for i in range(len(l)):
for j in range(i+1, len(l)+1):
ss = l[i] + l[i+1:j]
if target in ss:
result.append(ss)
return f'count = {len(result)}, substrings = {result}'
print(my_function("abcd,b"))
#count = 6, substrings = ['ab', 'abc', 'abcd', 'b', 'bc', 'bcd']
Here you go, this should help
from itertools import combinations
output = []
initial = input('Enter string and needed letter seperated by commas: ') #Asking for input
list1 = initial.split(',') #splitting the input into two parts i.e the actual text and the letter we want common in output
text = list1[0]
final = [''.join(l) for i in range(len(text)) for l in combinations(text, i+1)] #this is the core part of our code, from this statement we get all the available combinations of the set of letters (all the way from 1 letter combinations to nth letter)
for i in final:
if 'b' in i:
output.append(i) #only outputting the results which have the required letter/phrase in it

Managing duplicates when sorting by character order in string

I am trying to solve through a challenge where I have to reorder the letters in string s in the order it appears on string t. For example:
For s = "weather" and t = "therapyw", the output should be
sortByString(s, t) = "theeraw";
For s = "good" and t = "odg", the output should be
sortByString(s, t) = "oodg".
This is my code:
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
if t_list[i] in s_list:
output.insert(i, t_list[i])
return ''.join(output)
It works for all cases except if the same letter exists more than once.
s: "weather"
t: "therapyw"
Output:
"theraw"
Expected Output:
"theeraw"
How can I handle this situation in my code above? What am I missing? I appreciate all help but instead of just blurting out the answer, I would like to know what I'm doing wrong.
The issue with your current code is that it only adds one copy of each character in t to output, regardless of how many times it occurs in s. You can work around that by looping over the count of that character in s and appending to output for each count:
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
for _ in range(s_list.count(t_list[i])):
output.append(t_list[i])
return ''.join(output)
print(sortByString('weather',"therapyw"))
print(sortByString('good',"odg"))
Output:
theeraw
oodg
You can simplify the loop by just adding copies of a list with the current character according to the count of the character in s:
for c in t_list:
output = output + [c] * s_list.count(c)
Easy way
Use enumerate and turn your string into a dict
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
orderdict = {char: index for index, char in enumerate(t_list)}
output = sorted(list('weather'),key=orderdict.get)
return ''.join(output)
This will allow repeated values
Example
>>> sortByString('weather',"therapyw")
'theeraw'
Modification to OP's code
Just add the element number of times it appear in s to the output
def sortByString(s,t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
if t_list[i] in s_list:
output.append(t_list[i]*s_list.count(t_list[i]))
return ''.join(output)
output
>>> sortByString('weather',"therapyw")
'theeraw'
2 steps:
a. create a sorted list of characters in s and their order in t using index()
b. use zip(* to extract the sorted list of characters
s = "weather"
t = "therapy"
a = sorted([(t.index(c),c) for c in s])
b = ''.join(list(zip(*a))[1])
print(b)
Output:
theeraw

split or chunk dynamic string into specific parts and merging in python

Is there way to split or chunk the dynamic string into fixed size? let me explain:
Suppose:
name = Natalie
Family = David12
length = len(name) #7 bit
length = len(Family) # 7 bit
i want to split the name and family into and merging as :
result=nadatavilid1e2
and again split and extract the the 2 string as
x= Natalie
y= david
another Example:
Name = john
Family= mark
split and merging:
result= jomahnrk
and again split and extract the the 2 string as
x=john
y= mark
.
Remember variable name and family have different size length every time not static! . i hope my question is clear. i have seen some related solution about it like here and here and here and here and here and here and here but none of these work with what im looking for. Any suggestion ?? Thanks
i'm using spyder python 3.6.4
I have try this code split data into two parts:
def split(data):
indices = list(int(x) for x in data[-1:])
data = data[:-1]
rv = []
for i in indices[::-1]:
rv.append(data[-i:])
data=data[:-i]
rv.append(data)
return rv[::-1]
data='Natalie'
x,c=split(str(data))
print (x)
print (c)
Given you have stated names will always be of equal length you could use wrap to split in to 2 char pairs and the zip and chain to join them up. In the split part you can again use wwrap to split in 2 char pairs but if the number of pairs is odd then you need to split the last pair into 2 single entries. something like.
from textwrap import wrap
from itertools import chain
def merge_names(name, family):
name_split = wrap(name, 2)
family_split = wrap(family, 2)
return "".join(chain(*zip(name_split, family_split)))
def split_names(merged_name):
names = ["", ""]
char_pairs = wrap(merged_name, 2)
if len(char_pairs) % 2:
char_pairs.append(char_pairs[-1][1])
char_pairs[-2] = char_pairs[-2][0]
for index, chars in enumerate(char_pairs):
pos = 1 if index % 2 else 0
names[pos] += chars
return names
print(merge_names("john", "mark"))
print(split_names("jomahnrk"))
print(merge_names("stephen", "natalie"))
print(split_names("stnaeptaheline"))
print(merge_names("Natalie", "David12"))
print(split_names("NaDatavilid1e2"))
OUTPUT
jomahnrk
['john', 'mark']
stnaeptaheline
['stephen', 'natalie']
NaDatavilid1e2
['Natalie', 'David12']
Something like:
a = "Eleonora"
b = "James"
l = max(len(a), len(b))
a = a.lower() + " " * (l-len(a))
b = b.lower() + " " * (l-len(b))
n = 2
a = [a[i:i+n] for i in range(0, len(a), n)]
b = [b[i:i+n] for i in range(0, len(b), n)]
ans = "".join(map(lambda xy: "".join(xy), zip(a, b))).replace(" ", "")
Giving for this example:
eljaeomenosra

Categories