Count of a string in a list [duplicate] - python

This question already has answers here:
How do I count the occurrences of a list item?
(30 answers)
Closed 9 years ago.
I need help:
I want to write function that: takes a list as a input and return count of specific string.
If function input is x=[a,a,b,c] function need return 2 (a is two times in this list).

>>> def F(seq, string):
return seq.count(string)
>>> F(['a','a','b','c'], 'a')
2
Equivalent to:
def F(seq, string):
n = 0
for x in seq:
if x == string:
n += 1
return n

Related

python __divide list to multiple list based on ordered sequence of numbers [duplicate]

This question already has answers here:
Splitting list based on missing numbers in a sequence
(5 answers)
Closed 2 years ago.
I have this list
nums=[1,2,6,7,8,9,44,90,110,111,112]
I want to divide them into sub lists based on sequence
44 : there is no number before and after ;Excluded
90 same as 44
so the final output will be
finall_lst=[[1,2],[6,7,8,9],[110,111,112]]
I want that list to be dynamic so that it can receive any number of items even millions
thanks
Here's the solution to find group sequence from the list.
def groupSequence(x):
it = iter(x)
prev, res = next(it), []
while prev is not None:
start = next(it, None)
if prev + 1 == start:
res.append(prev)
elif res:
yield list(res + [prev])
res = []
prev = start
nums=[1,2,6,7,8,9,44,90,110,111,112]
print(list(groupSequence(nums)))

Python generate a list of consecutive numbers from a list of numbers [duplicate]

This question already has answers here:
Identify groups of consecutive numbers in a list
(19 answers)
How to pick consecutive numbers from a list [duplicate]
(2 answers)
Closed 4 years ago.
I have a list like this,
List1 = [1,2,3,7,8,11,14,15,16]
And I want to use python to generate a new list that looks like,
List2 = ["1:3", "7:8", "11", "14:16"]
How can I do this, is for loop the option here.
I don't want to use For loop as my list has more than 30 000 numbers.
You can use a generator:
List1 = [1,2,3,7,8,11,14,15,16]
def groups(d):
c, start = [d[0]], d[0]
for i in d[1:]:
if abs(i-start) != 1:
yield c
c = [i]
else:
c.append(i)
start = i
yield c
results = [str(a) if not b else f'{a}:{b[-1]}' for a, *b in groups(List1)]
Output:
['1:3', '7:8', '11', '14:16']

Finding a specific index? [duplicate]

This question already has answers here:
Determine prefix from a set of (similar) strings
(11 answers)
Closed 5 years ago.
If I have two strings, how can I find the index where the string stops matching?
'abcdefghijk' and the false alphabet 'abcdxyz', I know they stop matching at index 4, but how can I output that in a function setting?
Use the enumerate() function to find the index, for which the letter in the second string does not match the current letter in the first string -
def matcher(str1, str2):
for idx, item in enumerate(str1):
if item != str2[idx]:
return idx
return -1 # if no differing letter in second string
print(matcher('abcdefghijk', 'abcdxyz')) # 4
Using some simple comparisons of sliced strings:
We can create a simple function that keeps slicing the strings till it reaches the end of the first string and compares them:
def match(s1, s2):
for i in range(len(s1)+1):
if s1[:i] != s2[:i]:
return i - 1
return -1
and some tests:
>>> match('abcdefghijk', 'abcdxyz')
4
>>> match('124', '123')
2
>>> match('123456', '123abc')
3
>>> match("abcdef", "abcdef")
-1

how to count the letters in a string? [duplicate]

This question already has answers here:
How to count digits, letters, spaces for a string in Python?
(12 answers)
Closed 5 years ago.
how do I code a program that would produce this below?
As an example, the following code fragment:
print (count_letters("ab1c2d345"))
should produce the output:
4
You can try this:
def count_letters(s):
return len([i for i in s if i.isalpha()])
print(count_letters('ab1c2d345'))
Output:
4
Or, you can use regex for a cleaner solution:
import re
def count_letters(s):
return len(re.findall('[a-zA-Z]', s))
You can do it using simple loop/if statement.
def count_letters(str_ltr):
count_ltr = 0
for ch in str_ltr:
if ch.isalpha():
count_ltr += 1
return count_ltr
print(count_letters("ab1c2d345"))
Output: 4

How to count the number of a specific character at the end of a string ignoring duplicates? [duplicate]

This question already has answers here:
Pythonic way to count the number of trailing zeros in base 2
(5 answers)
Closed 5 years ago.
I have a series of strings like:
my_text = "one? two three??"
I want to count only the number of ? at the end of the string. The above should return 2 (rather than 3).
What I've tried so far:
my_text.count("?") # returns 3
There's not a built-in method for it. But something simple like this should do the trick:
>>> len(my_text) - len(my_text.rstrip('?'))
2
You could also use a regexp to count the number of trailing question marks :
import re
def count_trailing_question_marks(text):
last_question_marks = re.compile("\?*$")
return len(last_question_marks.search(text).group(0))
print count_trailing_question_marks("one? two three??")
# 2
print count_trailing_question_marks("one? two three")
# 0
Not so clean but simple way:
my_text = "one? two three??"
total = 0
question_mark = '?'
i = 0
for c in my_text:
i -= 1
if my_text[i] == question_mark:
total += 1
else:
break
One-liner using my favourite itertools:
First reverse the string, then continue iterating (taking the values) while our condition is satisfied (value == '?'). This returns an iterable which we exhaust into a list and finally take its length.
len(list(itertools.takewhile(lambda x:x=='?',reversed(my_text))))

Categories