Here I want to remove any vowels which repeat consecutively. But it shows error as "list out of index".
So I tried break if last element in list is reached, but still won't work.
Here is the code I tried:-
a=[]
b=str(input("enter the string"))
a=b.split(',')
c=['a','e','i','o','u']
for i in c:
for j in range(0,len(a)):
if (a[j+1] == a[len(a)]) is True:
break;
elif ((a[j] == a[j+1]) & (a[j+1] == i)) is True:
del[j]
e.join(a)
print(e)
Please show me how to solve this problem, or any other problem if in there.
How about maintaining a stack for consecutive vowels? whenever you see non-vowel string re-initialize the stack list and when you see vowels but are not consecutive you just add to the final list
stack=[]
new_list=[]
vowel=['a','i','o','u','e']
for i in your_string: # replace your string with actual string
if i not in vowel:
if len(stack) == 1:
new_list.append(stack[0])
new_list.append(i)
stack = []
else:
stack.append(i)
if len(stack) == 1:
new_list.append(stack[0])
You get a list out of index error because you are indexing at a value not in a
if (a[j+1] == a[len(a)]) is True:
a[len(a)] does not exist, arrays are zero indexed so they start from 0. An array with 5 items has index 0,1,2,3,4
the line should be:
if (a[j+1] == a[len(a) - 1]) is True:
Also 'is True' is redundant, so further refined:
if a[j+1] == a[len(a) - 1]:
Also is del[j] an error? should it be del a[j]?
If this is the case, the program will run into further errors as you are iterating over the entire Original size of the array but deleting values during this iteration, so it will look for items that no longer exist.
First detail is this: if (a[j+1] == a[len(a)]) is True: from what I understood this is to break the code when it is necessary. But that is completely unnecessary. Instead you should fix the number of iterations in the beginning, which should be for j in range(0,len(a)-1):
Another problem is that you aren't really iterating through the letters, just each comma separated phrases. If you put "Hello, World" you aren't checking the letters, you check "Hello" and " World". You might as well remove b and let a just be the raw input.
Since a would then be a string, to erase the i-th letter of a string you can use the function below.
def remove_jth(word, j):
word = word[:j] + word[j+1:]
Finally since you are using range, it will build a "list" that has the size len(a) when you start the for, but as you remove vowels, the length of a gets shorter and the range you had at the beginning will be to much. If you fix all of these things you should have it right
You can do it this way:
a=[]
b=str("a,a,a,b,e,e,e,c,x,d")
a=b.split(',')
c=['a','e','i','o','u']
j = 0
for i in c:
while j < len(a)-1:
if a[j] == a[j+1] and a[j] == i:
del a[j]
else:
j = j+1
j=0
Use a while loop to check through the list and delete consecutive duplicates. Then reset the the while loop back to zero and run through the list again.
Using a for loop will not work,if you are deleting items in the list that is being used to iterate over.
b=str("a,a,a,b,e,e,e,c,x,d") was just used to test the code.
To print the results you can just do print(a) it will print the list out.
I used this Stack Overflow post as reference.
I edited it to suit you:
result=original.replace('a','').replace('e',''),replace('i','').replace('o','').replace('u','')
original is your input string and result is your output string.
t=input()
st=""
vow=['a','e','i','o','u']
st+=t[0]
for i in range(1,len(t)):
if(t[i].lower() in vow):
if(t[i-1].lower() not in vow and i-1>=0):
st+=t[i]
else:
st+=t[i]
print(st)
Related
I know it can be simply done through string slicing but i want to know where is my logic or code is going wrong. Please Help!
S=input()
string=""
string2=""
list1=[]
list1[:0]=S
for i in list1:
if(i%2==0):
string=string+list1[i]
else:
string2=string2+list1[i]
print(string," ",string2)
Here's my code. Firstly i stored each character of string in the list and went by accessing the odd even index of the list.
But i'm getting this error
if(i%2==0):
TypeError: not all arguments converted during string formatting
You are iterating over characters, not indices, so your modulo is incorrect, equivalent to:
i = "a"
"a" % 2 == 0
You want to use enumerate
for idx, letter in enumerate(list1):
if(idx%2 == 0)
string += letter
You don't need to use an intermediate list: just iterate over the input string directly. You also need to use for i in range(len(original)) rather than for i in original, because you need to keep track of whether a given character is at an odd or an even index. (I've gone ahead and renamed some of the variables for readability.)
S = input()
even_index_characters = ""
odd_index_characters = ""
for i in range(len(S)):
if i % 2 == 0:
even_index_characters += S[i]
else:
odd_index_characters += S[i]
print(f"{even_index_characters} {odd_index_characters}")
Question Desc: Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just 1 character at 1 index in the string, and the remaining characters will occur the same number of times. Given a string s, determine if it is valid. If so, return YES, otherwise return NO.
def isValid(s):
lst = []
temp = []
for i in s:
y = i
lst.append(y)
st = set(lst)
for j in st:
count = s.count(j)
temp.append(count)
temp.sort()
print(temp)
b=temp[-1]-temp[-2]
ele = temp[0]
chk=True
for item in temp:
if ele!=item:
chk=False;
break;
if(chk==True):
print('YES')
break;
elif(b==1):
print('YES')
break;
else:
print('NO')
break;
For some reason , irrespective of my input , the answer seems to be YES. Can someone tell me where am I going wrong.
Link to the question
PS - You don't need an account to view the question , just click anywhere on the screen.
It's because of the initial values you've set for your variables. On the very first step of your iteration through temp you'll find that ele == item (because both are temp[0]), and then subsequently that chk == True (because you set it so). After the first step it'll print yes and break immediately.
I'm trying to make a function that takes in a string from a user and then outputs the same string. However for each letter in an even position it outputs the corresponding lower case letter, and for each letter in an odd position it outputs the corresponding uppercase letter. Keep in mind only one word will be passed through it at a time.
I've tried to create a for loop with an if statement nested within it, but so far, the for loop stops after iterating through the first letter. My code is below:
def converter(string):
for letters in string:
if len(letters) % 2 == 0:
return letters.lower()
elif len(letters)% 2 != 0:
return letters.upper()
When I run the code:
converter('app')
The output I get is 'A'
The expected output should be 'aPp'
The first thing you need to know is that in Python, strings are immutable. So "modifying" a string means you have to build a new string from scratch in (here, I call that newstring).
Second, you are misunderstanding the loop. You are saying for letters in string. This loop iterates over each letter of the string. On the first iteration, letters is the first letter of the strong. You then convert it to upper case (since the length of a single letter is always 1), and return it. You aren't reaching the rest of the letters! In the code below, I change the plurality to just letter to make this idea clear.
This amends all of those problems:
def converter(string):
newstring = ""
for i, letter in enumerate(string):
if i % 2 == 0:
newstring += letter.lower()
elif i % 2 != 0:
newstring += letter.upper()
return newstring
This can be boiled down to a nice list comprehension:
def converter(string):
return "".join([letter.lower() if i % 2 == 0 else letter.upper()
for i, letter in enumerate(string)])
In [1]: def converter(string):
...: return ''.join([j.upper() if i % 2 == 1 else j.lower() for i, j in enumerate(string)])
In [2]: converter('apple')
Out[2]: 'aPpLe'
''.join([s.lower() if c % 2 == 0 else s.upper() for c, s in enumerate('apple')])
# returns 'aPpLe'
first check for the condition, then iterate through the string using the nice old enumerate built-in.
This question already has answers here:
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Closed 6 months ago.
I am a beginner and am trying to write a piece of code that tells you how long the longest substring is that is written in alphabetic order.
So far I have:
s = 'azcbobobegghakl'
n=len(s)
i=0
longest=1
while i<n+1:
print(s[i])
if s[i] < s[i+1]:
longest+=1
i+=1
else:
i+=1
print(longest)
However I keep getting an error:
IndexError: string index out of range
Could somebody please tell me where I am going wrong and how to fix it
Try this:
s = 'azcbobobegghakl'
n=len(s)
longest=1
counter=1
for i in range(len(s)-1):
print(s[i])
if s[i] < s[i+1]:
counter+=1
else:
if counter > longest:
longest = counter
counter = 1
if counter > longest:
longest = counter
print(longest)
Change your condition in while loop like this
Change
while i < n-1:
Change n+1 to n-1
Reason:
n is length of string
Index of string : 0,1,.....,n-1
In your program one iteration will check next element also:
ie: when I == 0 , it will access str[0], str[1]
Like i == n - 2 , str[n-2], str[n-1]
Now if your condition is i less than n +1 then it will check
i == n , str[n], str[n+1] it will give you index out of range
because str[n+1] doesn't exist
Error that you are getting is IndexError: string index out of range in line 11 if s[i] < s[i+1]:. The problem is that i in while loop will become too big (bigger than n-1). Your loop condition should be while i<n-1: and NOT while i<n-1: like others have suggested in their answers. You are checking for each character in string s if it is smaller (if it appears before in alphabet, actually, Python check if it has a smaller Unicode code, so you need to use only lowercase or only uppercase letters) than the next character in the string. And you can check this for all characters in a string except the last one because the last character doesn't have successor (there is no next character after last one). That's why you should have i<n-1: in your while loop.
Full working code:
s = 'azcbobobegghakl'
n=len(s)
i=0
longest=1
print(n)
while i<n-1:
print(s[i])
if s[i] < s[i+1]:
longest+=1
i+=1
else:
i+=1
print(longest)
try this:
s = 'azcbobobegghakl'
n=len(s)
i=0
longest=1
while i<n:
print(s[i])
if i == n-1:
break
elif s[i] < s[i+1]:
longest+=1
i+=1
else:
i+=1
print(longest)
I'm writing the solution to this HackerRank problem - https://www.hackerrank.com/challenges/palindrome-index
I've tried this code:
T = int(raw_input())
for t in xrange(T):
s = raw_input()
index = -1
if s != s[::-1]:
for i in xrange(len(s)):
temp = s[:i:] + s[i+1::]
if temp == temp[::-1]:
index = i
break
print index
But when I submit it, out of the 14 test cases, around 8 take a long time to compute (~5-7 seconds) and 1 of them takes more than 10 seconds, so HackerRank doesn't even show the result (whether it gave the right output).
It seems my code is inefficient. Please help me out in making it run faster.
The easiest way to speed the code would be to remove slicing for every index in case that string isn't a palindrome. In case of maximum length string which is not a palindrome following line will generate over 200000 slices: temp = s[:i:] + s[i+1::].
You could start checking the string from start and beginning until you spot a difference. Once found you can generate slice which has either first or last letter removed and check if that's a palindrome. In case you removed the first character and result wasn't a palindrome you know that last character is the correct solution since the problem statement guarantees that:
T = int(raw_input())
for t in xrange(T):
s = raw_input()
length = len(s)
for i in xrange(length / 2):
if s[i] != s[length - i - 1]:
if s[i + 1:length - i] == s[length - i - 1:i:-1]:
print i
else:
print length - i - 1
break
else:
print -1
The most efficient way would be to check from both sides left and right and break on inequality:
for i in range(int(input())):
s=input()
if s==s[::-1]:
print(-1)
else:
for i in range(int(len(s)/2)):
if s[i]!=s[len(s)-1-i]:
print(i if ((s[:i]+s[i+1:])==(s[:i]+s[i+1:])[::-1]) else len(s)-1-i)
break
Apparently I'm a member of that site as well, executed my code and it passes all test cases with 0.01 s and 0.02s