couting a set of word in python - python-3.x

Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2
This is my answer, but i dont know what's wrong with my code. Please help
s = "azcbobobegghakl"
coutBob=0
i=0
for char in range (len(s)):
if char[i:i+3]=="bob":
coutBob+=1
else:
i=i+1
print ("Number of times bob occurs is: " + str(coutBob))

You need to subscript the string s, not the index:
for i in range(len(s)):
if s[i:i+3]=="bob":
coutBob+=1

I think this will help you.
b = list(s)
i = 0
j = 0
for i in range(0,len(b)-2):
if b[i]=='b' and b[i+1]=='o' and b[i+2]=='b':
j = j + 1
print ("Number of times bob occurs is: %d"%j)

Related

Count letters in sentences (Python)

i'm a beginner programmer, and i want to ask about count the many letters in a sentence.
For the example program like this :
data = "Hello World"
s = input() # Try to input L
Output :
L = 3
So the output is just what i input, not with other letters like w, o, r, d, h, e. I wrote some code but i dont know why the output sometimes None or 11 or 0. Here the code i write with output 0
data = "Hello World"
s = input()
sum = 0
for s in data :
if s == data :
sum += 1
print(sum)
Any suggestion for what i can do to write the program like i want ?
If I am not wrong, what I understood from your problem is that you wish to count the total number of times an alphabet appears in a string and then print the total number of times it occurred in the sentence.
In order to achieve this, I can show you two methods:
Method 1:
Naive approach:
data="Hello World"
s=input() # Assume you put 'l'
count = 0
for i in data:
if i == s:
count = count + 1
print(count)
Doing so, you will get output as 3
Method 2:
Using count():
data="Hello World"
counter = data.count('l')
print("Count of l in data is : " + str(counter))
Hope this answered you query.

How to split a number into individual digits VB using substring

I tried to put seconds in 2 text-boxes, each digit in one. Example x= 56 x1= 5 and x2= 6
' s = TimeOfDay.Second
TextBox15.Text = s.Substring(0, 1)
TextBox16.Text = s.Substring(1, 1)'
When I try this I get the following error: System.ArgumentOutOfRangeException
Any ideas on how to fix this?
ArgumentOutOfRange exceptions occurs whenever you attempt to get a character that doesn't exist at the given position. So what is happening is that there is either not a String at position 0 with a length of 1 or there is not a String at position 1 with a length of 1.
To prevent this, add a simple If/Then statement to check if the length of the original String at least equal to the position of the character. Also for what it's worth, since you only want one letter, simply get the character at the desired index of the String.
Here is a quick example:
If s.Length >= 1 Then
TextBox15.Text = s(0).ToString()
End If
If s.Length >= 2 Then
TextBox16.Text = s(1).ToString()
End If
Fiddle: Live Demo
You don't need to convert it to a string before getting the digits, just doing the maths to get them will work well enough:
Dim rightNow = DateTime.Now
TextBox15.Text = (rightNow.Second \ 10).ToString()
TextBox16.Text = (rightNow.Second Mod 10).ToString()
And another approach.
Dim c() As Char = DateTime.Now.Second.ToString("00").ToArray
TextBox1.Text = c(0)
TextBox2.Text = c(1)

Can someone explain to me why I get empty string as a result?

What im trying to do is get the longest substring in s in which the letters occur in alphabetical order.
For some reason alphasub has no string in it at the end and I don't know why
start = 0
sub = 1
maxsub = 0
current = 0
s = 'azcbobobegghakl'
leng = len(s)
for i in range(leng):
if i != leng - 1:
if s[i] <= s[i+1]:
current = i
sub = 1
while current < (leng-1):
if s[current] <=s [current+1]:
sub += 1
current += 1
else:
break
if(sub>maxsub):
maxsub = sub
start = i
alphasub = s[start:maxsub]
print("longest substring is: " + alphasub)
String slicing takes starting and end position.
https://docs.python.org/2/tutorial/introduction.html
Change alphasub=s[start:maxsub] to alphasub=s[start:start+maxsub]. You should see the expected output.
It's good practice to use print's to check your code.
I've added some prints at the end of your code like so:
print(s)
print(start)
print(maxsub)
alphasub=s[start:maxsub]
print ("longest substring is: " + alphasub)
Which outputs:
azcbobobegghakl
7
5
longest substring is:
It is starting at 7, and ending at 5, which obviously doesn't work.

Check if number has a digit multiple times

I've come across a puzzling challenge. I have to check if a number contains the same digit multiple times ex. 11, 424, 66 and so on. at first this seems easy enough but i'm having trouble coming up with a logic to check for this. any ideas?
This is what I've got so far. the function takes in a list. (updated)
arr = [[1,20],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for c in str(num):
if str(num).count(c) > 1:
# dont know why code is popping off 12 and 13
print(l.pop(num))
If your ultimate goal is simply detecting if there's a double, this function may help:
def has_doubles(n):
return len(set(str(n))) < len(str(n))
The best way I can think about is converting the number to a string and doing a Counter on it
from collections import Counter
a = 98
c = Counter(str(a))
if any(value > 1 for value in c.values()):
print "The number has repeating digits"
#Two-BitAlchemist thanks for the suggestion
looks like you wanted to create your own algorithm probably researching or a student practice well you just have to understand the properties of numbers divided by 10 where 1/10 = 0.1 10/10 = 1 13/10 = 1 reminder 3 13013/10 = 1301 rem 3 hence we can create a function that stores the reminders in an array an check them against the reminder of next number here is the algorithm in python using recursion, you can achieve the same via loops
def countNumber(foundDigits,number):
next_number = int(number/10);
reminder = number % 10;
if(next_number < 1):
for num in foundDigits:
if(num == number or num == reminder):
return True
return False;
foundDigits.append(reminder);
return countNumber(foundDigits,next_number)
example in interpreter could be
digitsFound = list()
countNumber(digitsFound, 435229)
Solved this! I didn't know pop executes based on position not value! remove is a better fit here.
arr = [[1,40],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for char in str(num):
if str(num).count(char) < 2: continue
l.remove(num)
break
print(l)
Here is my solution, its simple and works for 2 digit numbers.
nums = list(input().rstrip().split())
def has_doubles(nums):
for number in nums:
if number[0] == number[1]:
print(number)
else:
continue
has_doubles(nums)

Binary search code not working

Good afternoon everyone,
I'm trying to sort out names which are already sorted in alphabetical order. I can't figure out why my program isn't working. Any tips or pointers would be nice. Thanks.
def main():
names = ['Ava Fiscer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
input('Please enter the name to be searched: ', )
binarySearch
main()
def binarySearch(names):
first = 0
last = len(names) - 1
position = -1
found = False
while not found and first <= last:
middle = (first + last) / 2
if names[middle] == value:
found = True
position = middle
elif arr[middle] > value:
last = middle -1
else:
first = middle + 1
return position
What does it mean that the program isn't working? Is it a syntax error or is the problem in the wrong results?
With the code you pasted, there are several indentation problems, but besides that, lines:
input('Please enter the name to be searched: ', )
binarySearch
are also syntactically incorrect, the comma is redundant and only the function name appearing just like that is plain wrong. If you are interested in the correctness of your algorithm, it seems alright, but the boundaries can always be tricky. My code below is working and syntactically correct, if you find it helpful. (names are numbers, but that is irrelevant in this case)
names = [1,2,4,5,6,8,9]
def bs(n):
start = 0
end = len(names)
while end - start > 0:
m = (start+end)/2
if names[m] == n:
return m
elif n < names[m]:
end = m
else:
start = m + 1
return -1
print (bs(1))
print (bs(6))
print (bs(9))
print (bs(3))
print (bs(10))
print (bs(-8))
Another thing I would like to point out is that this kind of binary search is already in the python standard library, the bisect module. However, if you are writing your own for practice or for any other reason that is just fine.
if you are using python 3.* then you are going to want to change
m = (start+end)/2
to
m = (start+end)//2
When you do /2 it outputs a float in 3.*

Resources