replace an occurrence with a distinct number every loop - python-3.x

The first occurrence of the character in the string will be replaced with a 1, the second occurrence with a 2, etc.
ive tried using for loop and the max function to replace the last occurence but it doesnt seem to work.
string=str(input('string: '))
x=input('character: ')
list=[]
for i in range(len(string)):
if string[i]==x:
list.append(i)
Z=str(max(list))
print(string.replace(x,Z,[::-1]))
the output should be as following
string: departmentofcomputerscience
character: e
d1partm2ntofcomput3rsci4nc5

Here's a way to do it.
Use a counter for each character in the loop, and store values in the list, then merge the list. Use the current value if not equal to the character, counter otherwise:
string=str(input('string: '))
x=input('character: ')
# Use list to store results and a counter
l = []
counter = 0
for c in string:
if c==x:
counter += 1
l.append(str(counter))
else:
l.append(c)
# Merge the resulting list into string
res = "".join(l)
# Output the result
print(res)
For the input string: departmentofcomputerscience
and the character: e
The output is
d1partm2ntofcomput3rsci4nc5

Here is another way to achieve the goal using a list and the method replace():
string = str(input('string: '))
x = input('character: ')
list = []
for i in range(len(string)):
if string[i] == x:
list.append(i) # add all indexes to replace to the list
if len(list) > 0:
j = 0
for i in range(len(list)):
j += 1
string = string.replace(string[list[i]], str(j), 1) # replace the element once at time
print(string)
For string: departmentofcomputerscience
character: e
Output: d1partm2ntofcomput3rsci4nc5

def replace(s, c):
'''
#parameter s: input string
#parameter c: input character to be replaced
#return s: where every occurence of c is
replaced by it's nth occurence
'''
so = list(s)
j = 1
for i in range(len(so)):
if so[i] == c:
so[i] = str(j)
j = j + 1
return ''.join(so)

Related

Check how many consecutive times appear in a string

I want to to display a number or an alphabet which appears mostly
consecutive in a given string or numbers or both.
Example:
s= 'aabskeeebadeeee'
output: e appears 4 consecutive times
I thought about set the string then and for each element loop the string to check if equal with element set element if so count =+1 and check if next to it is not equal add counter value to list with same index as in set, if is add counter value to li list if value is bigger than existing.
The problem is error index out or range although I think I am watching it.
s = 'aabskeeebadeeee'
c = 0
t = list(set(s)) # list of characters in s
li=[0,0,0,0,0,0] # list for counted repeats
print(t)
for x in t:
h = t.index(x)
for index, i in enumerate(s):
maximus = len(s)
if i == x:
c += 1
if index < maximus:
if s[index +1] != x: # if next element is not x
if c > li[h]: #update c if bigger than existing
li[h] = c
c = 0
else:
if c > li[h]:
li[h] = c
for i in t:
n = t.index(i)
print(i,li[n])
print(f'{s[li.index(max(li))]} appears {max(li)} consecutive times')
Here is an O(n) time, O(1) space solution, that breaks ties by returning the earlier seen character:
def get_longest_consecutive_ch(s):
count = max_count = 0
longest_consecutive_ch = previous_ch = None
for ch in s:
if ch == previous_ch:
count += 1
else:
previous_ch = ch
count = 1
if count > max_count:
max_count = count
longest_consecutive_ch = ch
return longest_consecutive_ch, max_count
s = 'aabskeeebadeeee'
longest_consecutive_ch, count = get_longest_consecutive_ch(s)
print(f'{longest_consecutive_ch} appears {count} consecutive times in {s}')
Output:
e appears 4 consecutive times in aabskeeebadeeee
Regex offers a concise solution here:
inp = "aabskeeebadeeee"
matches = [m.group(0) for m in re.finditer(r'([a-z])\1*', inp)]
print(matches)
matches.sort(key=len, reverse=True)
print(matches[0])
This prints:
['aa', 'b', 's', 'k', 'eee', 'b', 'a', 'd', 'eeee']
eeee
The strategy here is to find all islands of similar characters using re.finditer with the regex pattern ([a-z])\1*. Then, we sort the resulting list descending by length to find the longest sequence.
Alternatively, you can leverage the power of itertools.groupby() to approach this type of problem (for quick counting for similar items in groups. [Note, this can be applied to some broader cases, eg. numbers]
from itertools import groupby
>>> char_counts = [str(len(list(g)))+k for k, g in groupby(s)]
>>> char_counts
['2a', '1b', '1s', '1k', '3e', '1b', '1a', '1d', '4e']
>>> max(char_counts)
'4e'
# you can continue to do the rest of splitting, or printing for your needs...
>>> ans = '4e' # example
>>> print(f' the most frequent character is {ans[-1]}, it appears {ans[:-1]} ')
Output:
the most frequent character is e, it appears 4
This answer was posted as an edit to the question Check how many consecutive times appear in a string by the OP Ziggy Witkowski under CC BY-SA 4.0.
I did not want to use any libraries.
s = 'aabskaaaabadcccc'
lil = tuple(set(s)) # Set a characters in s to remove duplicates and
then make a tuple
li=[0,0,0,0,0,0] # list for counted repeats, the index of number
repeats for character
# will be equal to index of its character in a tuple
for i in lil: #iter over tuple of letters
c = 0 #counter
h= lil.index(i) #take an index
for letter in s: #iterate ove the string characters
if letter == i: # check if equal with character from tuple
c += 1 # if equal Counter +1
if c > li[lil.index(letter)]: # Updated the counter if present is bigger than the one stored.
li[lil.index(letter)] = c
else:
c=0
continue
m = max(li)
for index, j in enumerate(li): #Check if the are
characters with same max value
if li[index] == m:
print(f'{lil[index]} appears {m} consecutive times')
Output:
c appears 4 consecutive times
a appears 4 consecutive times

logic for returning a substring with highest number of vowel

You are given with a string and length of a substring .You are required to determine the substring with highest number of vowels .The substring can be a combination of vowel and consonant but it should have the highest number of vowels.
example:
input
string= azerdii
length of substring=5
substrings= azerd,zerdi,erdii
erdii has highest number of vowels so output should be erdii
Kindly help me with the code in Python3
#fetch all substrings
string_is = 'azerdii'
sub = 5
length = len(string_is)
sub_ar = [string_is[i:j+1] for i in range(length) for j in range(i,length)]
#print(sub_ar)
#fetch substrings of a length = 5
sub_ar_is = []
for each in sub_ar:
if len(each) == 5:
sub_ar_is.append(each)
print(sub_ar_is)
data_dict = {}
data = ['a','e','i','o','u']
for each in sub_ar_is:
count = 0
for each_is in data:
count = count + each.count(each_is)
data_dict.update({each:count})
print(data_dict)
print("Substring is: ", max(data_dict, key=data_dict.get))
def findSubstring(s, k):
vowels = "aeiou"
return_output = ["Not found!"]
max_countt = 0
# loop size such that index don't gets out of range
length = len(s)-k+1
for i in range(length):
# temporary storage of vowel count
sum_count = 0
# getting string of desire size
output = s[i:i+k]
# count of vowels in the string
for vowel in vowels:
sum_count += output.count(vowel)
# if vowels in the string is greater than string having max vowels
# replace the max vowel string and number of max vowel count
if max_countt < sum_count:
return_output = output
max_countt = sum_count
# return output
return "".join(return_output)
print(findSubstring("azerdii", 5))

Problem with Python Code and the Functions in it

I have a Problem, I have to solve a task in Python and I dont know how to do it. The task is to define a function number_of_vowels, where the output should be the Number of vowels in a Word. With this function I have to write anotherone, many_vowels thats working with a list an a Number and where the number says how many vowels have to be at least in a word to be appended to the result list and then I have to append this Word. Thanks to everybody helping me ;D.
here is the code:
Wort = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
while result < 20:
if Word[counter0] == 'a' or 'e' or 'i' or 'o' or 'u':
result = result + 1
counter0 = counter0 + 1
else:
counter0 = counter0 + 1
return result
Words = []
counter1 = 0
def many_vowels(List , number):
if number_of_vowels(List[counter1]) < number:
counter1 + 1
else:
Words.append(List[counter1])
counter1 + 1
return Words
This code just gives me the answer to the letter a and not to the other vowels. For
print(number_of_vowels(Wort))
the output is: 1
but there are 4 vowels in this word
it also says: line 21, in many_vowels
IndexError: string index out of range
You're trying to call a function with wrong brackets. Function call should use round ones.
Try changing number_of_vowels[List[counter1]] with number_of_vowels(List[counter1])
This code contains some errors:
Calling for function should be using round brackets: number_of_vowels(List[counter1]) instead of number_of_vowels[List[counter1]]
doing result + 1 won't change value of the variable result, since you did not put the calculation result in the variable. use result = result + 1 (same for counters)
in number_of_vowels function, you want to scan the whole word? cause you did not use any loop, so it currently looking only at the first letter. Secondly, you put the compression in result and then add 1 to it. I'm not really sure why
edit:
Word = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
for index, letter in enumerate(Word):
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
result = result + 1
return result
Words = []
counter1 = 0
def many_vowels(List_name , number):
for index, item in enumerate (List_name):
if number_of_vowels(item) >= number:
Words.append(item)
return Words

How can I generate a list starting with the first value in a range?

I have a string that indicates a range of values: "A1C - A1H"
I need to be able to create a list of all the values in that range, meaning: ['A1C', 'A1D', 'A1E', 'A1F', 'A1G', 'A1H']
list = []
range = "A1C - A1H"
code = range[:2]
range_end = range[-3:]
for letter in ascii_uppercase:
order = code+letter
if order not in range_end:
list.append(order)
else:
list.append(range_end)
break
print(list)
The code runs, as is but it creates a list with the first 'A1A', 'A1B' values which I don't need:
['A1A', 'A1B', 'A1C', 'A1D', 'A1E', 'A1F', 'A1G', 'A1H']
How can I generate the list starting with 'A1C'?
Start the "for letter in ascii_uppercase" two char later
list = []
range = "A1C - A1H"
code = range[:2]
range_end = range[-3:]
count = 0
for letter in ascii_uppercase:
if count > 1:
order = code+letter
if order not in range_end:
list.append(order)
else:
list.append(range_end)
break
count += 1
print(list)
You can use the built-in ord and chr functions with a list comprehension instead to generate the desired list:
l = ['A1' + chr(i) for i in range(ord('C'), ord('H') + 1)]
l would become:
['A1C', 'A1D', 'A1E', 'A1F', 'A1G', 'A1H']
You can compare letter code and start loop when it is greater than starting point of string :
import string
def generate(string_data):
code = string_data[:2]
range_end = string_data[-3:]
sub_range = string_data[2:-6]
result=[]
for letter in string.ascii_uppercase:
if ord(letter)< ord(sub_range):
pass
elif code+letter == range_end:
result.append(code+letter)
break
else:
result.append(code+letter)
return result
output:
['A1C', 'A1D', 'A1E', 'A1F', 'A1G', 'A1H']
alternative solution:
This is not best solution but you can also slice the list from list in your code:
list_data = []
range_data = "A1C - A1H"
code = range_data[:2]
range_end = range_data[-3:]
for letter in string.ascii_uppercase:
order = code+letter
if order not in range_end:
list_data.append(order)
else:
list_data.append(range_end)
break
print(list_data[list_data.index(range_data[:3]):list_data.index(range_end)+1])
Note: Don't use list and range as variable name , They have special meaning in Python.

Use Python function to change string "oalalaeah" to "hello"

Hi I am learning python I was just trying to resolve the above example.That is make a function to change the string "oalalaeah" to "hello". Notice that 'hello' is the alternate letter starting from the back. I can do both individually. Important: I want to do it using only python functions()
`def rev_str(str1):
new_str = ''
index = len(str1)
while index > 0:
new_str += str1[index-1]
index = index - 1
return new_str`
print(rev_str('oalalaeah'))
to reverse the string to "haealalao"
later use:
def rev_alt(str2):
fin_str = ''
index = -2
while index < len(str2)-1:
fin_str += str2[index+2]
index = index + 2
return fin_str
print(rev_alt('haealalao'))
This gives me "hello" but these are 2 separate operations. I want to have 1 function that that will turn "oalalaeah" to "hello". I am sorry if this is too easy. Its driving me crazy
def rev_str(str1):
new_str = ''
index = len(str1)
while index > 0:
new_str += str1[index-1]
index = index - 1
return new_str
This is taking each letter in the string from the end to the beginning by decreasing the index by one on each iteration. Literally the only change needed to take every second letter is to decrease the index by two on each iteration:
def rev_str(str1):
new_str = ''
index = len(str1)
while index > 0:
new_str += str1[index-1]
index = index - 2 # 👈 here
return new_str
print(rev_str('oalalaeah')) # hello
The pythonic version of this is the built-in slice syntax:
print('oalalaeah'[::-2]) # hello

Resources