Python: Moving on to the next letter on For Loop - python

How can I move on to the next letter in a for loop before 1st iteration finishes?
s = 'mmmmbobob'
for letter in s:
if letter is 'b':
s = s + 1 <<<<<<<<<RIGHT HERE<<<<<<<<<
if letter is 'o':
s = s + 1 <<<<<<<<<THEN HERE<<<<<<<<<
if letter is "b":
counter_bob += 1
else:
break
else:
break
else:
continue
print('Number of times bob occurs is: %d' % (bob_name_counter))

Currently, you're trying to add 1 to the string s, which will throw a TypeError. Even if s was an int, incrementing it in this fashion would not move to the next iteration of the loop in Python (or any language I know).
You can use the keyword continue to move to the next iteration of a loop immediately. Docs here: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
However, I don't think that is exactly what you want to do here, since it looks like you are trying to count the occurrences of the substring 'bob' in your main string s.
Instead you should iterate over the indices of the characters of s and at each point check if the current character and next two together form the substring 'bob'. If so increment counter_bob.
An example refactor of your code with this in mind:
s = 'mmmmbobob'
counter_bob = 0
for i in range(len(s)):
if s[i:i+3] == 'bob':
counter_bob += 1
print('Number of times bob occurs is: %d' % (counter_bob))
Which prints:
Number of times bob occurs is: 2

Related

Most frequent character in Python 3.3

This program lets the user enter a string and displays the character that appears most frequently in a string.
I need help explaining frequent = i.
# This program displays the character that appears most frequently in the string
def main():
# Local variables.
count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
index = 0
frequent = 0
# Get input.
user_string = input('Enter a string: ')
for ch in user_string:
ch = ch.upper()
# Determine which letter this character is.
index = letters.find(ch)
if index >= 0:
# Increase counting array for this letter.
count[index] = count[index] + 1
# Please help me explain this entire part!
for i in range(len(count)):
if count[i] > count[frequent]:
frequent = i
print('The character that appears most frequently' \
' in the string is ', letters[frequent], '.', \
sep='')
# Call main
main()
The code snippet in question:
for i in range(len(count)):
if count[i] > count[frequent]:
frequent = i
First the for loop iterates over the length of count which is 26.
The if statement:
if count[i] > count[frequent]:
Checks to see if the current letter in the for loop is larger than the current most frequent character. If it is then it sets the new most frequent character as the index of the for loop.
For example,
If A is referenced 12 times and B is referenced 14 then on the second loop when i = 1 the if statement would look like this:
if 12 > 14:
frequent = 1
This sets frequent to 1 which can be used to find the frequency in count for ex.
count[1] == 14
There are 26 different items in the list count, and 26 letters in the charset. It iterates through the count list for each item (that's the for i in range (len(count)) part) and then sees if the value of that item is greater than the value of the current largest item it's found - simply speaking it finds the largest value in the array, but instead of getting the value it gets the index, frequent = i is setting the index of the largest value currently found as it iterates to the variable frequent. It's simpler and more pythonistic to simply do
frequent = index(max(count)
which has EXACTLY the same effect

Building 'Find' function in Python

I have been learning Python (as my first language) from "How to Think Like a Computer Scientist: Learning with Python". This open book teaches mostly through examples and I prefer to read the goal and build the program on my own, rather than actually reading the program code provided in the book.
However, I am struggling with creating a function which will search for a specific character in a given string and return how many times that character was counted.
The code I wrote is:
def find(s, x): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
else:
print count
However, when I run this code, I get the error "name 's' is not defined".
The code in the book has a slightly different goal: it searches for a specific character in a string, but instead of counting how many times the character was found, it returns the position of the character in the string.
def find(strng, ch, start=0, step=1):
index = start
while 0 <= index < len(strng):
if strng[index] == ch:
return index
index += step
return -1
I don't really understand this code, actually.
However, even when I run the code, for example, to search for 'a' in 'banana', I get the error name 'banana' is not defined.
What is wrong with my code? Could please someone explain me how the code provided in the book works?
1: There are a couple things wrong with this code. The function takes in two parameters, s and x, then immediately throws them away by overwriting those variables with user input. In your for loop, every time you encounter a character that isn't s you print the count. You should try to separate different ideas in your code into different methods so that you can reuse code more easily.
Break down your code into small, simple ideas. If the purpose of find is to count the instances of a character in a string, it shouldn't also be handling user interaction. If you take out the raw_input and printing, you can simplify this function to:
def find(s, x): #find s in x
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
return count
Now all it does it take in a character and a string and return the number of times the character appears in the string.
Now you can do your user interaction outside of the function
char = raw_input("Enter what you wish to find: ")
string = raw_input("Where to search?: )
print char + " appears " + `find(char, string)` + " times in " + string
2: The goal of this function is to find the first place where ch is found when walking through the characters strng from a starting position with a specified step. It takes in ch, strng, a position to start searching, and a step size. If the start is 0 and the step is 1, it will check every character. If the start is 2 it will check all but the first 2 characters, if the step is 2 it will check every other character, etc. This works by starting looking at the start index (index = start), then looping while the index is at least 0 and less than the length of the string. Since python is 0-indexed, the last character in the string has an index of one less than the length of the string, so this just restricts you from trying to check invalid indices. For each iteration of the loop, the code checks if the character at the current index is ch, in which case it returns the index (this is the first time it found the character). Every time it doesn't find the character at the current index, it increments the index by the step and tries again until it goes past the last character. When this happens it exits the loop and returns -1, a sentinel value which indicates that we didn't find the character in the string.
def find(strng, ch, start=0, step=1):
index = start
while 0 <= index < len(strng):
if strng[index] == ch:
return index
index += step
return -1
3: I'm guessing you passed some invalid parameters. strng should be a string, ch should be a single character, and start and step should be integers.
Try this. I took the parameters out of your function, moved the print command out of the else block and out of the for loop, and then wrote the last line to call the function.
def find(): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
print count
find()
It seems like you're taking in inputs s and x twice - once through the function arguments and once through raw input. Modify the function to do either one (say only from raw input - see below). Also, you only need to print out the count once, so you can place the print statement in the outermost indent level in the function.
def find(): #find s in x
s = raw_input("Enter what you wish to find: ")
x = raw_input("Where to search? ")
count = 0
for l in x: #loop through every letter in x
if l == s:
count += 1
print count

Trying to count the number of times a letter appears using only a while loop

I am trying to count how many o's there are in the raw input 'phrase' and it counts the first o and says it's done however there are many o's after that. How do I get it to count all of the o's with no for loop.
while loop_count<len(phrase):
if "o" in phrase:
loop_count += 1
count2 += 1
if loop_count>len(phrase):
print loop_count
break
else:
continue
else:
print loop_count
continue
You can use sum with an iterator (in this case a generator expression):
>>> sum(c=='o' for c in 'oompa loompa')
4
You can use a regex with len:
>>> re.findall('o', 'oompa loompa')
['o', 'o', 'o', 'o']
>>> len(re.findall('o', 'oompa loompa'))
4
You could use a Counter:
>>> from collections import Counter
>>> Counter('oompa loompa')['o']
4
Or just use the 'count' method of the string:
>>> 'oompa loompa'.count('o')
4
If you really want to use a while loop, use a list as a stack with the pop method:
s='oompa loompa'
tgt=list(s)
count=0
while tgt:
if tgt.pop()=='o':
count+=1
Or a 'for' loop -- more Pythonic:
count=0
for c in s:
if c=='o':
count+=1
you can use count function :
phrase.count('o')
but if you want to send a message after one match of 'o' for skip loop over the all of string just use 'in' look like this:
if 'o' in phrase :
# show your message ex: print('this is false')
Lets try to dissect your code you understand what is going on. See my comments
while loop_count<len(phrase):
if "o" in phrase: # See comment 1
loop_count += 1 # Why are you incrementing both of these?
count2 += 1
if loop_count>len(phrase): # What is this statement for? It should never happen.
## A loop always exits once the condition at the while line is false
## It seems like you are manually trying to control your loop
## Which you dont need to do
print loop_count
break # What does this accomplish?
else:
continue
else:
print loop_count
continue # Pointless as we are already at end of loop. Consider removing
Comment 1: You are asking if an 'o' is anywhere in the phrase. You instead want to ask if the current letter is an o. Perhaps you ment to access a LETTER of the phrase with the index, such as if 'o' == phrase[loop_count]. If you do this you want to increment loop_count every time, but the o count only when the letter is an o.
You could re-write it like this:
loop_count, o_count = 0, 0
while loop_count<len(phrase):
# loop_count represents how many times we have looped so far
if "o" == phrase[loop_count].lower(): # We ask if the current letter is 'o'
o_count += 1 # If it is an 'o', increment count
loop_count += 1 # Increment this every time, it tracks our loop count
print o_count
Using comprehensions
len([i for i in phrase if i=="o"])

Count number of occurrences of a character in a string

I'm just getting into Python and I'm building a program that analyzes a group of words and returns how many times each letter appears in the text. i.e 'A:10, B:3, C:5...etc'. So far it's working perfectly except that i am looking for a way to condense the code so i'm not writing out each part of the program 26 times. Here's what I mean..
print("Enter text to be analyzed: ")
message = input()
A = 0
b = 0
c = 0
...etc
for letter in message:
if letter == "a":
a += 1
if letter == "b":
b += 1
if letter == "c":
c += 1
...etc
print("A:", a, "B:", b, "C:", c...etc)
There are many ways to do this. Most use a dictionary (dict). For example,
count = {}
for letter in message:
if letter in count: # saw this letter before
count[letter] += 1
else: # first time we've seen this - make its first dict entry
count[letter] = 1
There are shorter ways to write it, which I'm sure others will point out, but study this way first until you understand it. This sticks to very simple operations.
At the end, you can display it via (for example):
for letter in sorted(count):
print(letter, count[letter])
Again, there are shorter ways to do this, but this way sticks to very basic operations.
You can use Counter but #TimPeters is probably right and it is better to stick with the basics.
from collections import Counter
c = Counter([letter for letter in message if letter.isalpha()])
for k, v in sorted(c.items()):
print('{0}: {1}'.format(k, v))

Print two appearances of character found in python list

First time here (and a programming noob), hope I get the formatting correct!
I'm trying to make a function that will print out where in a list the occurence of a sought after letter is placed. The code below finds the letter and prints out where in the list the letter is i.e. if you search for 'a' the program will answer it's in the 2nd spot (x+1).
The problem is, if I search for a letter that have more than one occurrencies (for example the letter 'e'), the program finds the letter in both spots but in both cases prints out that it is in the 10th spot.
I'm trying to find out why, should be 10th and 17th in this case.
# store string in variable
solution = list('can you guess me')
guess = raw_input('What letter do you guess on? ')
# Search list
def search(guess):
nothing = 0
for x in solution:
if x == guess:
print x,
print "is in ",
print solution.index(x) + 1
nothing = 1
if nothing == 0:
print "Couldn't find ",
print guess
search(guess)
If choosing e, like this:
What letter do you think is in the answer? e
the program prints out:
e is in 11
e is in 11
I would like to know why. :/
How about this approach:
solution = 'This is the solution'
# Search list
def search(guess):
return [i for i,x in enumerate(solution) if x == guess]
guess = raw_input('Enter your guess: ')
result = search(guess)
if result:
positions = ','.join(str(i+1) for i in result)
print('{0} was found in positions {1}'.format(guess, positions))
else:
print('Sorry, {0} was not found!'.format(guess))
What we are doing here is stepping through the solution and if a character matches the guess, we return its position. If no characters match, then the method will return an empty list; which is a falsey value.
Then, we just check the return value of the method. If it is a list, we add 1 to the position (since list indices start from 0), and then print those out.
solution.index(x) does the same search for you, but will only ever return the first match.
Use enumerate() instead to create an index:
for i, x in enumerate(solution):
if x == guess:
print x,
print "is in ",
print i + 1
nothing = 1
The alternative approach would be to tell solution.index() where to start searching from. The previous position you printed, for example:
last = -1
for x in solution:
if x == guess:
print x,
print "is in ",
last = solution.index(x, last) + 1
print last
nothing = 1

Categories

Resources