How to calculate the number of integers in a python string - python

I want to calculate the number of integers in the string "abajaao1grg100rgegege".
I tried using isnumeric() but it considers '100' as three different integers and shows the output 4. I want my program to consider 100 as a single integer.
Here is my attempt:
T = int(input())
for x in range(T):
S = input()
m = 0
for k in S:
if (k.isnumeric()):
m += 1
print(m)

I'd use a very basic regex (\d+) then count the number of matches:
import re
string = 'abajaao1grg100rgegege'
print(len(re.findall(r'(\d+)', string)))
# 2

Regex is the go-to tool for this sort of problem, as the other answers have noted. However, here is a solution that uses looping constructs and no regex:
result = sum(y.isdigit() and not x.isdigit() for x,y in zip(myString[1:], myString))
In addition, here is an easy to understand, iterative solution, that also doesn't use regex and is much more clear than the other one, but also more verbose:
def getNumbers(string):
result = 0
for i in range(len(string)):
if string[i].isdigit() and (i==0 or not string[i-1].isdigit()):
result += 1
return result

You can use the regex library to solve this issue.
import re
st = "abajaao1grg100rgegege"
res = re.findall(r'\d+', st)
>>> ['1', '100']
You can check how many numbers you have on that list that the findall returned.
print (len(res))
>>> 2
In order to read more on python regex and the patterns, enter here

Not very Pythonic but for beginners more understandable:
Loop over characters in string and in every iteration remember in the was_digit (logical variable) if the current character is digit - for the next iteration.
Increase the counter only if the previous character was not a digit:
string = 'abajaao1grg100rgegege'
counter = 0 # Reset the counter
was_digit = False # Was previous character a digit?
for ch in string:
if ch.isdigit():
if not was_digit: # previous character was not a digit ...
counter += 1 # ... so it is start of the new number - count it!
was_digit = True # for the next iteration
else:
was_digit = False # for the next iteration
print(counter) # Will print 2

random="1qq11q1qq121a21ws1ssq1";
counter=0
i=0
length=len(random)
while(i<length):
if (random[i].isnumeric()):
z=i+1
counter+=1
while(z<length):
if (random[z].isnumeric()):
z=z+1
continue
else:
break
i=z
else:
i+=1
print ("No of integers",counter)

Related

How to count instances of consecutive letters in a string in Python 3?

I want to count the number of instances where consecutive letters are identical in a given string.
For example, my string input is:
EOOOEOEE
I would only like to find the number of occasions where there is more than one consecutive 'O'.
The Output should be:
1
Since, there is only one set of O's that come consecutively.
This is possible with itertools.groupby:
from itertools import groupby
x = 'EOOOEOEE'
res = sum(len(list(j)) > 1 for i, j in groupby(x) if i == 'O') # 1
You can use a regex:
>>> import re
>>> s = 'EOOOEOEEOO'
>>> sum(1 for x in re.finditer(r'O{2,}', s))
2
Just count with a for-loop:
n = 0
g = 0
s = 'EOOOEOEE'
for c in s:
if c == 'O':
g += 1
elif g:
if g > 1:
n += 1
g = 0
if g:
n += 1
which gives n as 1.
I assume you want to know the number of times that all letters are consecutive in a string and not just for the letter 'O'.
Make a character dictionary that will hold this count as values to keys as the characters in a string. char_dict = {}
The idea is to have two conditions to match
(1) Is the current character same as the previous character
(2) If the first condition is true then is the current pair of consecutive characters part of a larger substring that has the same consecutive characters.
Simply put, take for example ABBBCBB. When we encounter the third B we want to check whether it is part of sub-string that is consecutive and already accounted for. i.e. BBB should give consecutive count to be 1 and not 2. To implement this we use a flag variable that checks this conditions.
If we use only the (1)st condition BBB will count as BB and BB and not as a single BBB.
Rest of the code is pretty straight forward.
char_dict = {}
string = "EOOOEOEEFFFOFEOOO"
prev_char = None
flag=0
for char in list(string):
if char not in char_dict:
#initialize the count by zero
char_dict[char] = 0
if char == prev_char and flag !=0:
char_dict[char] += 1
flag = 0
else:
flag = 1
prev_char = char
print(char_dict)

Python: list index out of range when trying to compare two strings at index?

I have this function to check if a string contains three or more lowercase letters.
def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
i = 0
flag = 0
while i <= len(word):
j = 0
while j <= len(lowCharList):
if lowCharList[j] == word[i]:
flag += 1
j = 0
else:
j += 1
i += 1
if flag >= 3:
return True
In simple terms, I pass in a string (word) and create a list of acceptable characters (lowCharList).
Then, I set up a nested while loop that checks word[i] at every index of lowCharList, until it finds a match.
Then it resets lowCharList counter and adds 1 to flag, and moves on to word[i+1].
If it doesn't find a match by the time it reaches z, then it moves onto word[i+1] anyways.
For some reason, why I try my sample input in my main function.
def main():
word = 'corRe!33'
print(lowerCaseValid(word))
I get this error:
in lowerCaseValid
if lowCharList[j] == word[i]:
IndexError: list index out of range
Why is it throwing this error? Thank you.
using python's in operator is easier...
def lowerCaseValid(word):
cnt = 0
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
chars = lowCharList.pop ()
for ch in word:
if ch in chars:
cnt += 1
return cnt >= 3
or with using sets just 2 lines of code
def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
return len(set(lowCharList.pop()) & set(word)) >=3
or one liner with map and lambda
def lowerCaseValid(word):
return len(list(map(lambda x: x.islower, list(word)))) >=3
Another alternative approach using a list comprehension and string.ascii_lowercase instead of redefining the lowercase letters:
from string import ascii_lowercase
def lowerCaseValid(word):
return sum[x in ascii_lowercase for x in word] >= 3
How this works is that the list comprehension goes through each letter in word. The x in ascii_lowercase will return a boolean value of either True (1) or False (0), then sum up the Trues
Change
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
to
lowCharList = list('abcdefghijklmnopqrstuvwxyz')
I believe this should help, since you have a list containing only 1 item, whereas this way, you create a list with 24 items (all different letters).
As heemayl pointed out in the comments, lowCharList is 1 element long! Now you have 2 options: make lowCharList an actual list (lowCharList = list ("abcd...")), or keep lowCharList a string, which will work just fine (remove the brackets in the definition.
Might I suggest another method: checking if str.islower count adds up to >=3. So:
lower_count = 0
for letter in word:
if letter.islower(): lower_count += 1
if lower_count >= 3: return True
Also, as suggested in the comments:
return len ([letter for letter in word if letter.islower()]) >= 3
would work (better than my answer, which is just the expanded form of it)

How to count number of words inside a string using a for loop in python 3

I am trying to write a for loop that finds a specific word inside a string. I know that there is a one liner to do this in python, but I am practicing the for loops and I want to see how using a for I can identify specific words as it identifies especific letters (like vowels). I've been reading some questions, and I think the code should go like this:
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
answer = 0
for i in range(len(s)):
if any(s[i:].startswith(b) for b in s):
answer += 1
print(answer)
but it is not printing anything. I did something similar when I was looking for vowels in the same string, but now I know I am supouse to "arrange" the characters in the word "banana" and then comparate it to the string, that is the porpuse of this part:
if any(s[i:].startswith(b) for b in s):
if you could help me I would really apreciate it.
Thank you.
Your code doesn't print because you don't call the function(you only define it), you should call the function by adding a command at the end:
count_words(s,b)
Your function actually count the number of character in string s:
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
answer = 0
# Loop over each character in s
for i in range(len(s)):
# create a list contain at least current character => any will always return True
if any(s[i:].startswith(b) for b in s):
answer += 1
print(answer)
Right codes:
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
answer = 0
for i in range(len(s)):
if s[i:].startswith(b):
answer += 1
print(answer)
count_words(s,b)
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
answer = 0
counter = 0
if b in s:
for i in range(len(s)):
if s[i]!=b[counter]:
counter=0
else:
counter+=1
if counter == len(b):
answer+=1
counter = 0
print(answer)
count_words(s, b)
Above algorithm first check whether banana exists in s at least once. Then, it will loop to find the count.
If your goal is to use a for loop, you could find the length of the word you're looking for, then check sections of the larger string that are the same length and see if they match. You don't need to use any unless you are intentionally wanting to. Something like this:
s='bananasdasdnansbanana'
b='banana'
def count_words(s,b):
word_length = len(b)
answer = 0
for i in range(len(s) - len(b) + 1):
if s[i:i+word_length] == b:
answer += 1
return answer
count_words(s,b)
Note I also changed your print to return. It works either way.

Python While loops with tuples

I am writing a function which should count the numbers in an inputted phrase. That phrase gets stored as a tuple and the while loop should count the number of vowels. So far I have gotten this.
def whilephrase():
vowels=['A','a','E','e','I','i','O','o','U','u']
print('Please give me a phrase')
inputphrase=input()
inputphrase=tuple(inputphrase)
i=0
while True:
if vowels in inputphrase:
i=i+1
else:
print(i)
But this just prints out an endless loop of zeros.
You need to iterate over your inputphrase:
for character in inputphrase:
if character in vowels:
i = i + 1
print(i)
But there is, of course, an easier way:
def count_vowels(string):
return sum(1 for c in string if c.lower() in "aeiou")
edit: Using a while loop (although I'm not sure why you want specifically that):
index = 0
i = 0
while index < len(inputphrase):
if inputphrase[index] in vowels:
i += 1
index += 1
print(i)
print len([i for i in inputphrase if i in vowels])
you can also use collections
from collections import Counter
sum([Counter(inputphrase)[i] for i in vowels])

noob python question, extract letter from list

not sure why this isn't working.
error I'm getting: ord() expected a character, but string of length 0 found
code:
phrase = 'test'
number = 0
text = 0
random1 = ''
while (number <= len(phrase)):
letter = phrase[number:number+1]
text = ord(letter) - ord('a')
....
number = number + 1
if a print letter, i get the t for the first iteration
thanks,
You are failing on your last iteration. Because you let number take the value len(phrase), you are trying to slice your string beyond the end.
For example:
>>> "abc"[3:4]
''
String indices range from 0 to len(s)-1.
BTW: Python gives you much nicer ways to iterate over strings:
phrase = 'test'
for letter in phrase:
text = ord(letter) - ord('a')
....
You are iterating past the end of phrase, try this:
phrase = 'test'
number = 0
text = 0
random1 = ''
while (number < len(phrase)):
letter = phrase[number:number+1]
text = ord(letter) - ord('a')
Note the:
while (number < len(phrase)):
You do indeed have to show more code. What is i? Are you incrementing it each loop?
Typically, if you ARE incrementing i to act just like a for loop, you want to loop such that number < len(phrase), not <=.
Also, you can replace
letter = phrase[number:number+1]
with
letter = phrase[number]
Use for..in instead to process each letter in your string:
Code:
phrase = 'test'
for letter in phrase:
print letter
Output:
t
e
s
t
This would be the more "pythonic" way of doing character iteration. This way you're guaranteed to hit every letter without having to consider hitting the end, as what's happening in your code.
You want a char and not a string, right? Try to replace your
letter = phrase[number:number+1]
with
letter = phrase[number]

Categories