Accept an string if the pattern has the same count value Python - python

I'm trying to make a program that prints if a string is accepted or not under the condition that the number of times a pattern appears in the sequence has the same count value; for example: 'aaabbbccc' would be accepted but not 'aabccc'. I have some ideas of how to implement it, but I'm stuck. Any advice would be helpful, thanks a lot
# B = {a^n b^n c^n | n ≥ 0}
string = 'aaabbbccc'
count_a = 0
count_b = 0
count_c = 0
for i in string:
if i == 'a':
count_a += 1
elif i == 'b':
count_b += 1
elif i == 'c':
count_c += 1
else:
pass
if count_a == count_b and count_b == count_c:
print('String accepted')
else:
print('Not accepted')

You're looking to accept the language B = {a^n b^n c^n | n ≥ 0}. A concise method of checking this is:
def accept_b(s):
n = len(s) - len(s.lstrip('a'))
return len(s) == 3*n and s[n:2*n] == 'b'*n and s[2*n:] == 'c'*n

from collections import Counter
test_str = "aabbccc"
counter = Counter(test_str)
print(len(set(counter.values())) == 1)
so the Counter counts the amount of times each char is repeated and then we check
how many different values are inside the dictionary. if they are all the same then the length is 1.

Just count each unique characters in the string and if character count is not equal then return "Not accepted" else "String Accepted"
def character_counter(string):
set_string = set(string)
current_count = 0
for char in set_string:
if current_count == 0:
current_count = string.count(char)
else:
count_char = string.count(char)
if count_char!=current_count:
return 'Not accepted'
return 'String accepted'

Related

Using Python, how to print output string as -> aaa3bb2c1ddddd5 when Input string is aaabbcddddd

Using Python, how to print output string as -> aaa3bb2c1ddddd5 when Input string is aaabbcddddd
I want to concatenate actual character value and number of times a character is repeated in a string
def mycode(myString):
lenstr = len(myString)
print('length of string is '+str(lenstr));
for ele in myString:
count=0
for character in myString:
if character == ele:
count = count+1
totalstr = ele+str(count)
return totalstr
If the string is always sorted and grouped together like that, then you can use a collections.Counter to do it.
from collections import Counter
inp = "aaabbcddddd"
counter = Counter(inp)
out = "".join(k * v + str(v) for k,v in counter.items())
Or in one line:
print(''.join(k * v + str(v) for k,v in Counter(inp).items()))
Output:
aaa3bb2c1ddddd5
Or you can do it manually:
inp = "aaabbcddddd"
last = inp[0]
out = inp[0]
count = 1
for i in inp[1:]:
if i == last:
count += 1
else:
out += str(count)
count = 1
last = i
out += i
out += str(count)
print(out)
Here is a one line solution using a regex replacement with callback:
inp = "aaabbcddddd"
output = re.sub(r'((\w)\2*)', lambda m: m.group(1) + str(len(m.group(1))), inp)
print(output) # aaa3bb2c1ddddd5
Another one-liner:
import itertools
test = 'aaabbcddddd'
out = ''.join(f"{(g := ''.join(ig))}{len(g)}" for _, ig in itertools.groupby(test))
assert out == 'aaa3bb2c1ddddd5'
def char_counter_string(string):
prev_char = None
char_counter = 0
output = ''
for char_index in range(len(string)+1):
if char_index == len(string):
output += str(char_counter)
break
if string[char_index] != prev_char and prev_char is not None:
output += str(char_counter)
char_counter = 0
output += string[char_index]
char_counter += 1
prev_char = string[char_index]
return output
if __name__ == '__main__':
print(char_counter_string('aaabbcddddd'))
you can do like..
Code:
Time Complexity: O(n)
input_string="aaabbcddddd"
res=""
count=1
for i in range(1, len(input_string)):
if input_string[i] == input_string[i-1]:
count += 1
else:
res+=input_string[i-1]*count + str(count)
count = 1
res+=input_string[-1]*count + str(count)
print(res) #aaa3bb2c1ddddd5
Here's another way, ...
Full disclosure: ... as long as the run of characters is 10 or less, it will work. I.e., if there are 11 of anything in row, this won't work (the count will be wrong).
It's just a function wrapping a reduce.
from functools import reduce
def char_rep_count(in_string):
return reduce(
lambda acc, inp:
(acc[:-1]+inp+str(int(acc[-1])+1))
if (inp==acc[-2])
else (acc+inp+"1"),
in_string[1:],
in_string[0]+"1"
)
And here's some sample output:
print(char_rep_count("aaabbcdddd"))
aaa3bb2c1dddd4
I think this fulfils the brief and is also very fast:
s = 'aaabbcddddd'
def mycode(myString):
if myString:
count = 1
rs = [prev := myString[0]]
for c in myString[1:]:
if c != prev:
rs.append(f'{count}')
count = 1
else:
count += 1
rs.append(prev := c)
rs.append(f'{count}')
return ''.join(rs)
return myString

Character counter should not display amount if amount is 1

def encode(message):
encoded_message = ""
i = 0
while (i <= len(message)-1):
count = 1
ch = message[i]
j = i
while (j < len(message)-1):
if (message[j] == message[j+1]):
count = count+1
j = j+1
else:
break
encoded_message=encoded_message+str(count)+ch
i = j+1
return encoded_message
#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)
This code generates the following output: 1A4B8C1A1B
But if the value is 1 it should just display the letter like this: A4B8CAB
Simply replace this line:
encoded_message=encoded_message+str(count)+ch
with this:
encoded_message += (str(count) if count > 1 else "") + ch
It should do the trick. Now it only appends the count to the string if said count is bigger than one.

Find the total number of occurrence of a string in a cyclic string

I'm currently learning Python and I'm stuck on this specific question.
Image
Here is my current code:
word = input()
text = 0
wordch = 0
positions = 0
repeated = 0
while repeated != 2:
for i in range(0, len(tablet)):
if tablet[i] == word[wordch]:
text += 1
wordch += 1
if text == len(word):
positions += 1
text = 0
wordch = 0
elif repeated == 1 and text == len(word):
positions += 1
text = 0
wordch = 0
break
elif i == len(tablet)-1:
repeated += 1
break
elif tablet[i] != word[wordch]:
text == 0
wordch == 0
print(positions)
I would hope for a code that is really basic using the same concepts but please do answer.
Thank you!
I have tried to solve the problem by using a different approach. As we know that we can only use (len(fav_word)) - 1 letters if we tried to create the substring in a cyclic manner from the end since if we took any more characters, we would have created them from the start itself without the cycle.
So, I just created a new string from the original string by appending the starting (len(fav_word)) - 1 to the original string and then find all occurrences of the fav_string in the new string.
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += 1
x = "cabccabcab"
fav = "abc"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 3
x = "ababa"
fav = "aba"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 2
x = "aaaaaa"
fav = "aa"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 6
x = "abaaba"
fav = "aaba"
y = x + x[0:len(fav)-1]
print(len(list(find_all(y, fav)))) # Output: 2
def find_str(g,find):
lg = len(g)
lf = len(find)
x=0
s=""
for index, i in enumerate(g):
if i == find[0]:
if index+lf <= lg:
s = "".join(g[index:index+lf])
if s == find:
x+=1
else:
rem = "".join(g[index:])
lr = len(rem)
for index,i in enumerate(g):
rem+=i
lr+=1
if lr == lf:
if rem == find:
x+=1
break
return x
print(find_str("abaaba","aaba"))
def split(word):
return [char for char in word]
x = "aaaaaa"
pattern = "aa"
mylist=split(x)
ok=True
occurrences=0
buffer=""
while ok:
char=mylist.pop(0)
buffer+=char
if buffer==pattern:
occurrences+=1
buffer=""
if len(mylist)==0:
ok=False
print(occurrences)
output:3

IndexError: String Index out of range for recursive function

So I am learning python and am trying to count the number of vowels in a sentence. I figured out how to do it both using the count() function and an iteration but now I am trying to do it using recursion. When I try the following method I get an error "IndexError: string index out of range". Here is my code.
sentence = input(": ")
def count_vowels_recursive(sentence):
total = 0
if sentence[0] == "a" or sentence[0] == "e" or sentence[0] == "i" or sentence[0] == "o" or sentence[0] == "u":
total = total + 1 + count_vowels_recursive(sentence[1:])
else:
total = total + count_vowels_recursive(sentence[1:])
return the_sum
print(count_vowels_recursive(sentence))
Here are my previous two solutions.
def count_vowels(sentence):
a = sentence.count("a")
b = sentence.count("e")
c = sentence.count("i")
d = sentence.count("o")
e = sentence.count("i")
return (a+b+c+d+e)
def count_vowels_iterative(sentence):
a_ = 0
e_ = 0
i_ = 0
o_ = 0
u_ = 0
for i in range(len(sentence)):
if "a" == sentence[i]:
a_ = a_ + 1
elif "e" == sentence[i]:
e_ = e_ + 1
elif "i" == sentence[i]:
i_ = i_ + 1
elif "o" == sentence[i]:
o_ = o_ + 1
elif "u" == sentence[i]:
u_ = u_ + 1
else:
continue
return (a_ + e_ + i_ + o_ + u_)
You have no base case. The function will keep recursing until sentence is empty, in which case your first if statement will cause that index error.
You should first of all check if sentence is empty, and if so return 0
You can shorten things up quite a bit:
def count_vowels_recursive(sentence):
# this base case is needed to stop the recursion
if not sentence:
return 0
# otherwise, sentence[0] will raise an exception for the empty string
return (sentence[0] in "aeiou") + count_vowels_recursive(sentence[1:])
# the boolean expression `sentence[0] in "aeiou"` is cast to an int for the addition
You can try this:
def count_vowels_recursive(s, count):
if not s:
return count
else:
new_count = count
if s[0] in ["a", "e", "i", "o", "u"]:
new_count += 1
return count_vowels_recursive(s[1:], new_count)

Trying to find the next prime number

MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1

Categories