Use Python function to change string "oalalaeah" to "hello" - python-3.x

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

Related

I am trying to write a program that prints out the input string in reversed order from end to beginning

string = str(input("Please type in a string: "))
index = 0
while index < len(string):
print(string[index])
index += -1
I am getting an error that says (string index out of range)
strings in python are kinda like lists. You can use print(string[::-1]) to print backwards
Edit:
To print character by character
string = string[::-1]
index=0
while index < len(string):
print(string[index])
index += 1
The reason you are getting 'Index out of range' error is that your while condition will never be false since your index will almost always be less than 0.
This should fix that:
string = str(input())
index = len(string) - 1; # Start at the end of your string
while index > -1: # Until you have reached the end
print(string[index])
index -= 1 # Equivalent to 'index += -1' but cleaner

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

replace an occurrence with a distinct number every loop

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)

How to find the index of the nth ocurrence of a character in a string

"/home/hernan/PycharmProjects/test1/tensor.py".find('e') #Returns 4
"/home/hernan/PycharmProjects/test1/tensor.py".find('e',2) #Also 4
"/home/hernan/PycharmProjects/test1/tensor.py".find('e',3) #Also 4
I would like something like:
"/home/hernan/PycharmProjects/test1/tensor.py".find('e',2) #Returns 7
"/home/hernan/PycharmProjects/test1/tensor.py".find('e',3) #Returns 14
Those are the second and third ocurrences of 'e'.
Any built-in function in Python 3.x to get the index of the nth ocurrence of a character in a string?
Why not just use a for-loop?
def find_nth(text, sub, nth):
start = -1
for i in range(nth):
start = text.find(sub, start + 1)
if start == -1:
break
return start
find_nth("/home/hernan/PycharmProjects/test1/tensor.py", 'e', 2) # returns 7
find_nth("/home/hernan/PycharmProjects/test1/tensor.py", 'e', 3) # returns 24
The second argument in the str.find function is to indicate the start index. Not the index of the occurrence to start looking from. 'find a char'.find('a', 3) is equivalent to 'find a char'[3:].find('a') + 3 (sort of; not dealing with the search string not being present in the full string that it's being searched for in). You'll have to write your own function for this.
def search(full, toFind, occ):
ret = 0
while occ:
ret = full.find( toFind, ret ) + 1
occ -= 0
if ret == -1:
return -1
return ret

Run length encoding python; String index out of range error

I'm trying to implement run length encoding into python with this code.
When I run it I get string index out of range error, not sure what is causing the error though
text="aaabbbcc"
def encode(text):
prev = text[0]
lentext = len(text)
i = 1
while prev == text[i] and i < lentext:
i += 1
return prev + str(i) + encode(text[i:])
print(encode(text))
Before you can check if i is less than the text length, you already try to access the ith element of text, which causes the exception. Instead, write your while loop as:
while i < lentext and prev == text[i]:
This will make sure i is in range before trying to access that index of text.
Also note that if you are going to use a recursive algorithm, you need a base case to exit the chain of recursive calls from. Probably something like the following at the top of your function:
if not text:
return ""
So all together:
text="aaabbbcc"
def encode(text):
if not text:
return ""
prev = text[0]
lentext = len(text)
i = 1
while i < lentext and prev == text[i]:
i += 1
return prev + str(i)+ encode(text[i:])
print(encode(text))

Resources