I want to write a code to count number of words in a given sentence by using character comparison and below is the code I have written as I am not allowed to use some fancy utilities like split(), etc. So, could you please guide me where am I making mistakes' I am a novice in python and currently trying to fiigure out how to do charactery by character comparison so as to find out simple counts of words, lines, strings withous using built in utitilites. So, kindly guide me about it.
Input Sentence : I am XYZ
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
while(Input_Sentence[i] != "\n"):
if(Input_Sentence[i] == ' '):
count=count+1
i+=1
else:
i+=1
print ('Number of Words in a given sentence is :' +str(count))
At first I wouldn't use a while loop in this context. Why not using a for loop?
for char in Input_sentence:
With this you iterate over every letter.
Then you can use the rest of you code and check:
if char == ' ':
# initialize the counter
word_count = 0
last_space_index = 0
# loop through each character in the sentence (assuming Input_Sentence is a string)
for i, x in enumerate(Input_Sentence): # enumerate to get the index of the character
# if a space is found (or newline character for end of sentence)
if x in (' ', '\n'):
word_count += 1 # increment the counter
last_space_index = i # set the index of the last space found
if len(Input_Sentence) > (last_space_index + 1): # check if we are at the end of the sentence (this is in case the word does not end with a newline character or a space)
word_count += 1
# print the total number of words
print 'Number of words:', word_count
The following will avoid errors if there's an space at the beginning or the end of the sentence.
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
sentence_length = len(Input_Sentence)
for i in range(sentence_length):
if Input_Sentence[i] == " ":
if i not in (0, sentence_length - 1):
count += 1
count += 1
print "There are %s words in the sentence \"%s\"." % (count, Input_Sentence)
You may use try-except syntax.
In your code you used while(Input_Sentence[i] != "\n") to find when the sentence comes to an end. If you just print the output at every step before i+ = 1 like this:
...
while(Input_Sentence[i] != "\n"):
...
print i,Input_Sentence[i]
i+=1
else:
print i,Input_Sentence[i],'*'
i+=1
...
you can see for yourself that the output is something like this:
Enter your sentence: Python is good
Python is good
0 P *
1 y *
2 t *
3 h *
4 o *
5 n *
6
7 i *
8 s *
9
10 g *
11 o *
12 o *
13 d *
Traceback (most recent call last):
File "prog8.py", line 19, in <module>
while(Input_Sentence[i] != "\n"):
IndexError: string index out of range
which means that the code that you have written works fine upto the length of the input sentence. After that when i is increased by 1 and it is demanded of the code to check if Input_Sentence[i] == "\n" it gives IndexError. This problem can be overcome by using exception handling tools of Python. Which leaves the option to neglect the block inside try if it is an exception and execute the block within except instead.
Input_Sentence = raw_input("Enter your sentence: ")
print Input_Sentence
count = 0
i=0
try:
while (Input_Sentence[i] != "\n"):
if (Input_Sentence[i] == ' '):
count=count+1
i+=1
else:
i+=1
except:
count = count+1
print ('Number of Words in a given sentence is :' +str(count))
Related
i find a code to seperate line, but it cut hafl of word "A very very long str" \n "ing from user input". so i want to ask how to keep the original word. its mean add \n after a number of word?
# inp = "A very very long string from user input"
# new_input = ""
# for i, letter in enumerate(inp):
# if i % 20 == 0:
# new_input += '\n'
# new_input += letter
#
# # this is just because at the beginning too a `\n` character gets added
# new_input = new_input[1:]
# print(new_input)
Using a simple loop on a list of the words:
inp = "A very very long string from user input"
start = 0
N = 3
l = inp.split()
for stop in range(N, len(l)+N, N):
print(' '.join(l[start:stop]))
start = stop
output:
A very very
long string from
user input
update: splitting with a max number of characters
If you need this, don't reinvent the wheel, use textwrap.wrap:
inp = "A very very long string from user input"
from textwrap import wrap
print('\n'.join(wrap(inp, width=20)))
output:
A very very long
string from user
input
I see that there is already an accepted answer, but I'm not sure that it completely answers the original question. The accepted answer will only split the string provided into lines with 3 words each. However, what I understand the question to be is for the string to be split into lines of a certain length (20 being the length provided). This function should work:
def split_str_into_lines(input_str: str, line_length: int):
words = input_str.split(" ")
line_count = 0
split_input = ""
for word in words:
line_count += 1
line_count += len(word)
if line_count > line_length:
split_input += "\n"
line_count = len(word) + 1
split_input += word
split_input += " "
else:
split_input += word
split_input += " "
return split_input
inp = "A very very long string from user input"
length = 20
new_input = split_str_into_lines(inp,length)
print(new_input)
new_input
Giving result:
"""
A very very long
string from user
input
"""
or
'A very very long \nstring from user \ninput '
Try using str.split() 1 and give it space as a delimiter:
words = inp.split(' ')
That should return a list of words
Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's if the number of times the characters appears is not exactly 1.
Ex: If the input is:
n Monday
the output is:
1 n
Ex: If the input is:
z Today is Monday
the output is:
0 z's
Ex: If the input is:
n It's a sunny day
the output is:
2 n's
Case matters. n is different than N.
Ex: If the input is:
n Nobody
the output is:
0 n's
This is what I have so far:
user_string=input(str())
character=user_string[0]
phrase=user_string[1]
count=0
for i in phrase:
if i == character:
count = count+1
if count!= 1:
print(str(count) + " " + character + "'s")
else:
print(str(count) + " " + character)
This works great for the phrases that have 0 characters matching. But its not counting the ones that should match.
user_string=input(str())
character=user_string[0]
phrase=user_string[1:]
count=0
for i in phrase:
if i == character:
count = count+1
if count != 1:
print(str(count) + " " + character + "'s")
else:
print(str(count) + " " + character)
We will take the user's input, with the assumption that the first letter is the one that you are counting, and find that character with user_string.split()[0]. We will then take all the other words from the user's input (with user_string.split()[1:]), join them with ''.join and then explode them into a list of letters with [*]. We will return a list of "hits" for the character we are looking for. The length of that list will be the number of "hits".
user_string=input()
numOfLetters = [letter for letter in [*''.join(user_string.split()[1:])]
if user_string[0]==letter]
print(f'Number of {user_string[0]} is: {len(numOfLetters)}')
t This is a test # Input
Number of t is: 2 # Output
h Another test for comparison # Input
Number of h is: 1 # Output
Suggest just using str.count.
user_string = input()
character, phrase = user_string[0], user_string[1:]
count = phrase.count(character)
print(f"{count} {character}" + "'s" if count != 1 else '')
user_phrase=input()
letter=user_phrase[0]
if letter in user_phrase:
if user_phrase.count(letter)>2:
print (f'{user_phrase.count(letter)-1} {letter}\'s')
elif user_phrase.count(letter)==1:
print(f'0 {letter}\'s')
else:
print(f'{user_phrase.count(letter)-1} {letter}')
letter_and_phrase = str(input())
number_times_char_appears = 0
begin_letter = letter_and_phrase[0]
split_phrase = letter_and_phrase[1:].strip(' ')
for letter in split_phrase:
if letter in begin_letter:
number_times_char_appears += 1
if number_times_char_appears > 1:
print(f"{number_times_char_appears} {begin_letter}'s")
elif number_times_char_appears == 0:
print(f"{number_times_char_appears} {begin_letter}'s")
else:
print(f"{number_times_char_appears} {begin_letter}")
I am new to python and I was trying to write a program that gives the frequency of each letters in a string from a specific point. Now my code is giving correct output for some inputs like if I give the input "hheelloo", I get the correct output, but if the input is "hheelllloooo", the frequency of h,e and l is printed correct, but the frequency of 'o' comes out as 7 if the starting point is index 0. Can somebody tell me what am i doing wrong.
Write a Python program that counts the occurrence of Character in a String (Do
not use built in count function.
Modify the above program so that it starts counting
from Specified Location.
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1
str = list(map(str, input("Enter the string : ")))
count = 1
c = int(input("Enter the location from which the count needs to start : "))
for i in range(c, len(str)):
for j in range(i+1,len(str)):
if str[i] == str[j]:
count += 1
str[j] = 0
if str[i] != 0:
print(str[i], " appears ", count, " times")
count = 1 // <----- This line should be outside the if block.
The error was because of indentation.
I have just properly indented the last line.
Thanks, if it works, kindly upvote.
string module can be useful and easy to calculate the frequency of letters, numbers and special characters in a string.
import string
a='aahdhdhhhh2236665111...//// '
for i in string.printable:
z=0
for j in a:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
If you want to calculate the frequency of characters from a particular index value, you just have to modify the above code a little as follows:
import string
a='aahdhdhhhh2236665111...//// '
c = int(input("Enter the location from which the count needs to start : "))
for i in string.printable:
z=0
for j in a[c:]:
if i==j:
z+=1
if z!=0:
print(f'{i} occurs in the string a {z} times')
I don't think you need to map the input to list of str as input() always returns a string and string itself is a list of characters. Also make sure you don't use the built-ins as your variable names (As str used in your code). One of the simpler approach can be:
input_word = input("Enter the string : ")
c = int(input("Enter the location from which the count needs to start : "))
# Dict to maintain the count of letters
counts = {}
for i in range(c, len(input_word)):
# Increment 1 to the letter count
counts[input_word[i]] = counts.get(input_word[i], 0)+1
for letter, freq in counts.items():
print (f'{letter} appears {freq} times')
Output:
Enter the string : hheelllloooo
Enter the location from which the count needs to start : 2
e appears 2 times
l appears 4 times
o appears 4 times
For example: string = aaaacccc, then I need the output to be 4a4c. Is there a way to do this without using any advanced methods, such as libraries or functions?
Also, if someone knows how to do the reverse: turning "4a4c: into aaaacccc, that would be great to know.
This will do the work in one iteration
Keep two temp variable one for current character, another for count of that character and one variable for the result.
Just iterate through the string and keep increasing the count if it matches with the previous one.
If it doesn't then update the result with count and value of character and update the character and count.
At last add the last character and the count to the result. Done!
input_str = "aaaacccc"
if input_str.isalpha():
current_str = input_str[0]
count = 0
final_string = ""
for i in input_str:
if i==current_str:
count+=1
else:
final_string+=str(count)+current_str
current_str = i
count = 1
final_string+=str(count)+current_str
print (final_string)
Another solution and I included even a patchwork reverse operation like you mentioned in your post. Both run in O(n) and are fairly simple to understand. The encode is basically identical one posted by Akanasha, he was just a bit faster in posting his answer while i was writing the decode().
def encode(x):
if not x.isalpha():
raise ValueError()
output = ""
current_l = x[0]
counter = 0
for pos in x:
if current_l != pos:
output += str(counter) + current_l
counter = 1
current_l = pos
else:
counter += 1
return output + str(counter) + current_l
def decode(x):
output = ""
i = 0
while i < len(x):
if x[i].isnumeric():
n = i + 1
while x[n].isnumeric():
n += 1
output += int(x[i:n])*x[n]
i = n
i += 1
return output
test = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasasggggggbbbbdd"
test1 = encode(test)
print(test1)
test2 = decode(test1)
print(test2)
print(test == test2)
yes, you do not need any libraries:
list1 = list("aaaacccc")
letters = []
for i in list1:
if i not in letters:
letters.append(i)
string = ""
for i in letters:
string += str(list1.count(i))
string+=str(i)
print(string)
Basically, it loops through the list, finds the unique letters and then prints the count with the letter itself. Reversing would be the same function, just print the amount.
I am a beginner to python, and I was tasked with creating a function that accepts a string as the parameter and return the number of words in the string.
I am having trouble with the spaces and the blank string I assigned. I feel like I am missing something, but am a bit lost as to what's missing or what I've messed up. Also we can't use split.
Any guidance or help would be greatly appreciated
This is what I have so far:
def word_count(str):
count = 1
for i in str:
if (i == ' '):
count += 1
print (count)
word_count('hello') --> Output = 1 (so far correct)
word_count('how are you?') --> Output = 3 (also correct/at least what i am looking for)
word_count(' this string has wide spaces ') --> Output = 7 (Should be 5...)
word_count(' ') --> Output = 2 (Should be ''. I think it's doing count(1+1))
use this code as an improvement
def word_count(str):
count = 1
for i in str:
if (i == ' '):
count += 1
if str[0] == ' ':
count -= 1
if str[-1] == ' ':
count -= 1
print (count)
your error is because your counting spaces if they start at beginning or appear at end.
NOTE that you can't pass empty string "" since this is evaluated to NONE, and trying to index it will cause an error
The problem seems to be when there is a blank in front or behind the sentence. A way to fix this is by using a built in function 'strip'. For example, we can do the following:
example_string = " This is a string "
print(example_string)
stripped_string = example_string.strip()
print(stripped_string)
The output of the first string will be
" This is a string "
The output of the second string will be
"This is a string"
What you can do is the following:
def word_count(input_str):
return len(input_str.split())
count = word_count(' this is a test ')
print (count)
It basically removes the leading/trailing spaces and splits the phrase into
a list.
If, on the offchance you need to use a loop:
def word_count(input_str):
count = 0
input_str = input_str.strip()
for i in input_str:
if (i == ' '):
count += 1
return count
count = word_count(' this is a test ')
print (count)