I want to solve the below question:
Input_str - "I love Programming in Python"
Initialise 'n_cnt' as 0 and 'output' as 0
v='aeiouAEIOU'
FOR every w in input_str.split()
Initialise cnt to 0
FOR every c in w
check IF c is present in v
if true, increment 'cnt' by 1
end inner for loop
check IF 'cnt' is greater than or equal to 'n_cnt'
if true, assign 'cnt' to 'n_cnt' and assign 'w' to 'output'
end outer for loop
Print 'output'
Here's my code:
Input_str="I love Programming in Python"
n_cnt=0
output=0
v='aeiouAEIOU'
Split=Input_str.split()
for w in Split:
cnt=1
for c in w:
if c in v:
cnt=cnt+1
break
if cnt>=n_cnt:
cnt=n_cnt
output=w
print(output)
What am I doing wrong?
I am not quite sure what your motive is with this program but I assume you want to count the number of vowels in a particular string:
So, here is my implementation:
string = "I love Programming in Python"
vowel_cnt = 0
for i in string:
if i in "aeiouAEIOU":
vowel_cnt += 1
print("number of vowels = ", vowel_cnt)
First, you initialize a counter to 0, then you iterate through all the indices of the string one by one and check if the element at that index is in the String with all the vowels i.e "aeiouAEIOU", if yes, you increment the counter by 1.
First, use StackOverflow code editor to create python indentations, so the code can be easily read. Also, try to state your problem clearly, so when someone solves it, you can check that the result is what you want. The following code seems to be the correct version of your source code, it splits the sentence into words and selects the words that contain one character from v.
Input_str="I love Programming in zzzz Python"
n_cnt=0
output=0
v='aeiouAEIOU'
Split=Input_str.split()
print(Split)
for w in Split:
cnt=1
for c in w:
if c in v:
cnt=cnt+1
break
if cnt >= n_cnt:
n_cnt=cnt
output=w
print(output)
also you said in your question that cnt should be assigned to n_cnt but in your codes you did it incorrectly. The above source code will skip zzzz and print the other words in each line.
Related
The question for the code is 'input a word and check whether the first character of the word is repeated in the word again or not. If yes then change all the repeating characters to $ except the first character.'
So I coded the following and used the logic to start the loop from the second character of the word so that first character remains unchanged.
a=input()
for i in range(1,len(a)):
if(a[i]==a[0]):
b=a.replace(a[i],'$')
print(b)
for the above program I gave the input as 'agra' and to my surprise got the output as '$gr$'. the first character was also changed.
What is the problem with my logic? and what other solution do you suggest?
That is more simply done like:
Code:
b = a[0] + a[1:].replace(a[0], '$')
Test Code:
a = 'stops'
b = a[0] + a[1:].replace(a[0], '$')
print(b)
Results:
stop$
For the correct solution in python, see Stephen Rauch's answer.
I think that what you where trying to achieve, in a very "unpythonic" way, is:
a = input()
b = a # b is a copy
for i in range(1, len(a)):
if a[i] == a[0]:
# replace i-th char of b by '$''
print (b)
How to do that replacement? In python: strings are immutable, that means you cannot replace a char "in place". Try to do this:
a='agra'
a[3] = '$'
And you'll get an error:
TypeError: 'str' object does not support item assignment
If you want to replace the i-th char of a string by $, you have to write:
b = b[:i] + '$' + b[i+1:]
That is: build a new string from b[0], ..., b[i-1], add a $ and continue with b[i+1], ..., b[len(a)-1]. If you use this in your code, you get:
a = input()
b = a
for i in range(1, len(a)):
if a[i] == a[0]:
b = b[:i] + '$' + b[i+1:]
print (b)
Okay, it works but don't do that because it's very "unpythonic" and inefficient.
BEGIN EDIT
By the way, you don't need to replace, you can just build the string character by character:
a = input()
b = a[0] # start with first char
for i in range(1, len(a)):
if a[i] == a[0]:
b += '$' # $ if equals to first char
else:
b += a[i] # else the current char
print (b)
END EDIT
That gave me this idea:
a=input()
b="".join('$' if i!=0 and c==a[0] else c for i,c in enumerate(a))
print(b)
Explanation: the list comprehension takes all characters of a along with their position i (that's what enumerate does). For every couple position, character, if the position is not 0 (not the first character) and if the character is equal to a[0], then put a $. Else put the character itself. Glue everything together to make a new string.
Again, that's not the right way to do what you are trying to do, because there is another way that is neater and easier (see Stephen Rauch's answer), but is shows how you can sometimes handle difficulties in python.
a=input()
for i in range(1,len(a)):
if(a[i]==a[0]):
b=a[1:len(a)].replace(a[i],'$')
print(a[0]+b)
you changed whole word/sentence 'a': a.replace(...)
I don't know what kind of problem this is called and couldn't find something related to this on the site. I am trying to make a function that prints out the first letter of the word on the first line then the next two letters and so on. However, I am not sure on how to prevent repeating the complete word. For example in the word 'bar', it should go
b
ba
bar
ba
b
but my function repeats bar twice. Thanks!
a= []
def letters():
x = input("Enter a string")
count = 0
for c in x:
count +=1
y = 0
while y <= count:
z = (x[:y])
a.append(z)
y += 1
negWords = a[::-1]
for words in a:
print (words)
for words in negWords:
print (words)
You seem to be doing some unnecessary work for simply wanting to print something. You can make use of len to get the length of the word, without having to go through a loop to get the size.
Also, collecting the data in a list seems unnecessary.
To stick to the nature of your approach with the while loop, you can go through the entire length of the word and back again until "0". So, to me, I see that as twice the length of the word. With that in mind, that would be my control for the while loop. I would simply then check for when my incrementer reaches about the length of the word, and start going backwards from there:
w = "bar"
l = len(w)
i = 0
while i <= l*2:
if i > l:
print(w[:(l - i)])
else:
print(w[:i])
i += 1
Output:
b
ba
bar
ba
b
Try this:
negWords= a[:-1:-1]
This will not include the full word a second time
Also, your code could use a lot of cleanup. For example:
count = len(x)
Makes more sense than what you have
I'm taking the MIT 6 Programming with Python course for kicks and for a problem set everyone, teach included, wrote their for loop like this:
s="whataboutbob"
for char in range(len(s)):
Isn't that the same as:
s="whataboutbob"
for char in s:
why would someone use the range and len functions if you can just use the variable? What am I missing? I'd ask them but im doing the course solo and the forums are empty-ish. Thanks.
They're not the same thing.
for char in s:
print(char)
Will print the characters in s. I.e 'w', 'h', 'a', etc.
for n in range(len(s)):
print(n)
Will print the numbers 0, 1, 2, etc.
If you need to do some sort of operation with the indices of a list or a string in python, then you would use the range function. In that sense, iterating over a range provides more flexibility.
Another alternative when using a for loop is using the enumerate function. If you were to write
s="whataboutbob"
for n, char in enumerate(s):
then in your loop you would be able to use the variable n to refer to the index in the string, and the variable char to refer to the actual character at that index.
for char in range(len(s)): iterates over numbers from zero to length of string, another loop iterates over characters of string: w,h,a,t,... It is not the same.
The len() function takes the number of characters that you are currently on, starting from 0. For instance in apple, the a would be 0, the p would be 1 etc.
On the other hand
for char in (variable):
print char
would print each letter in that variable, so like
a-p-p-l-e.
It is NOT the same thing:
s="whataboutbob"
for char in s:
print(char)
Would give us a result of
w
h
a
t
a
b
o
u
t
b
o
b
whilst
s="whataboutbob"
for char in range(len(s)):
print(char)
would give us this result:
0
1
2
3
4
5
6
7
8
9
10
11
I'm taking MIT 6.00.1x from edX.org and I'm on problem set 1 problem 2. I'm having trouble getting bob from this variable
s = 'azcbobobegghakl'
I have this code
s = 'azcbobobegghakl'
bobTimes = 0
for bobWord in s:
if 'b' and 'o' and 'b' in bobWord:
bobTimes += 1
print(bobTimes)
The code works for this variable, but when you add on another b and o, like this:
s = 'azcbobobegghaklbobddbtto'
It adds one to the bobTimes variable. I don't see how I can extract the word 'bob' from this variable.
Just get the next 3 characters of the string using python's list slices.
s = 'azcbobobegghakl' #prints 2
s = 'azcbobobegghaklbobddbtto' #prints 3
bobTimes = 0
for i in range(len(s)):
if s[i:i+3] == 'bob':
bobTimes += 1
print(bobTimes)
Could you clarify the extraction requirements? Specifically:
is bobob two bobs, or just one? is bobobob three? or must they all be seperate i.e. bobasdfbobwwwwbob
s.count("bob") would count how many instances of "bob" occur with non overlapping letters. i.e bob is 1, bobbob is 2, bobob is only one because the middle b only counts towards the first one, leaving only ob, but bobobob is 2 better read as bob o bob
you could iterate through the characters one at a time, and check if that character and the next 3 are equal to "bob"
for k,v in enumerate(s):
if s[k:k+3]=="bob": bobcount+=1
this approach counts bobob as two, and bobobob as three.
or you could resort to using regular expressions, but thats not my strong suit, and i'll leave that to someone else to explain/update a bit later with info on that.
# -*- coding:UTF-8 -*-
str= "Green tree"
scr= "e"
cstr= len(str)
n=0
a=0
while n < cstr:
if str[n] == scr:
print(len(scr))
n=n+1
I have to count "e" in -str- string, but when I run this script I get
1
1
1
1
instead of 4.
What's the problem?
First of all, don't use str as a variable name, it will mask the built-in name.
As for counting characters in a string, just use the str.count() method:
>>> s = "Green tree"
>>> s.count("e")
4
If you are just interested in understanding why your current code doesn't work, you are printing 1 four times because you will find four occurrences of 'e', and when an occurrence is found you are printing len(scr) which is always 1.
Instead of printing len(scr) in your if block, you should be incrementing a counter that keeps track of the total number of occurrences found, it looks like you set up a variable a that you aren't using, so the smallest change to your code to get it to work would be the following (however as noted above, str.count() is a better approach):
str= "Green tree"
scr= "e"
cstr= len(str)
n=0
a=0
while n < cstr:
if str[n] == scr:
a+=1
n=n+1
print(a)
Use the count method:
>>> st="Green tree"
>>> st.count('e')
4
If the count method is broken on your Python ;-), you can use a for loop:
st="Green tree"
tgt='e'
i=0
for c in st:
if c==tgt: i+=1
print i
# 4
If you really want a while loop:
idx=0
i=0
while idx<len(st):
if st[idx]==tgt: i+=1
idx+=1
print i
But, this being Python, a more 'Pythonic' approach if your count method broken is to use sum on a generator expression:
>>> sum(1 for c in st if c=='e')
4
scr= "e"
##
print(len(scr))
For why it's doing this, it's doing what you asked, and printing the length of the variable scr, which is always one.
You're best to use the str.count() method as others mentioned, or increment a counter yourself manually.