So i was solving a question that is in my Lab practical Syllabus. Below is the question:-
Write a python class to reverse a sentence (initialized via
constructor) word by word. Example: “I am here” should be reversed as
“here am I”. Create instances of this class for each of the three
strings input by the user and display the reversed string for each, in
descending order of number of vowels in the string.
Below is code for the implementation of above question:-
class sentenceReverser:
vowels = ['a','e','i','o','u']
vowelCount =0
sentence=""
reversed_string = ""
def __init__(self,sentence):
self.sentence = sentence
self.reverser()
def reverser(self):
self.reversed_string = " ".join(reversed(self.sentence.split()))
return self.reversed_string
def getVowelCount(self):
for i in self.sentence:
if i.lower() in self.vowels:
self.vowelCount += 1
return self.vowelCount
inp = []
for i in range(2):
temp = input("Enter string:- ")
ob = sentenceReverser(temp)
inp.append(ob)
sorted_item = sorted(inp,key = lambda inp:inp.getVowelCount(),reverse=True)
for i in range (len(sorted_item)):
print('Reversed String: ',sorted_item[i].reverser(),'Vowel count: ',sorted_item[i].getVowelCount())
Below is output i am getting for the above code:-
issue:-
Could someone tell me why i am getting double the vowel count???
Any help would be appreciated!!
You are calling getVowelCount() twice. Instead you can use the variable instead of calling in the print command
for i in range (len(sorted_item)):
print('Reversed String: ',sorted_item[i].reverser(),'Vowel count: ',sorted_item[i].vowelCount)
This is because you don't reset vowel count in the method. So if you execute the method once (here in sort), you'll get correct count. If you execute it twice (in printing), you will get twice as much. If you execute it once more, you'll get 3x correct amount. And so on.
The solution is to reset the number:
def getVowelCount(self):
self.vowelCount = 0
for i in self.sentence:
if i.lower() in self.vowels:
self.vowelCount += 1
return self.vowelCount
Or to calculate it only once - set it to None, then calculate only if self.vowelCount is None, otherwise return existing value.
Related
Given a string, I want to write 3 separate functions:
first_word is to print the first word of the string
second_word is to print the second word of the string
last_word is to print the last word of the string
If the string has 2 words in total, the output from function 2 should be equal to function 3.
Example:
sentence = "once upon a time there was a programmer"
print(first_word(sentence)) # once
print(second_word(sentence)) # upon
print(last_word(sentence)) # programmer
What I tried so far:
def first_word(str):
space = str.find(' ')
return(str[0:space])
sentence = "once upon a time there was a programmer"
print(first_word(sentence))
Output:
once
What I'm stuck on:
I'm not sure how to do the second and third functions. Is there a way to have function 1 incorporated into function 2 and 3? Then the only difference between the 3 functions is that they're different iterations of function 1. Please explain your thought process as well.
use :
def finder(str, value):
space = str.split(' ')
if value == "first":
return space[0]
elif value == "second":
return space[1]
elif value == "last":
return space[-1]
sentence = "once upon a time there was a programmer"
print(finder(sentence, "first"))
print(finder(sentence, "second"))
print(finder(sentence, "last"))
You can form a list of all the strings in the given sentence and the use the corresponding indices to get the word you want as demonstrated below
class Word_Finder:
def __init__(self,sentence):
self.sentence = sentence
self.word_list = self.sentence.split() #splits the sentence
def first_word(self):
return self.word_list[0]
def second_word(self):
return self.word_list[1]
def last_word(self):
return self.word_list[-1]
sentence = "once upon a time there was a programmer"
words = Word_Finder(sentence)
print(words.first_word())
print(words.second_word())
print(words.last_word())
Here , I am assuming that your sentence will always have 2 or more words.
To lessen the bloat of using def functions, we could use a simple lambda function that uses the split() operation.
This may look something like this:
sentence = "once upon a time there was a programmer"
find_word = lambda index: sentence.split(" ")[index]
find_word can now be given any arbitrary index to list any word you may want.
find_word(0) # returns 'once'
find_word(1) # returns 'upon'
find_word(-1) # returns 'programmer'
A def function implementation would be:
def find_word(sentence, index) -> String:
# except when index is outside of sentence length
try:
return sentence.split(" ")[index]
except IndexError:
return ""
You can use string split method to get words from your sentence https://www.w3schools.com/python/ref_string_split.asp
#!/usr/bin/env python3
# coding=utf-8
sentence = 'once upon a time there was a programmer'
def get_words(input):
return input.split(" ")
def first_word(data):
words = get_words(data)
if len(words) != 0:
print(f"First word = {words[0]}")
def second_word(data):
words = get_words(data)
if len(words) > 1:
print(f"Second word = {words[1]}")
else:
print("Second word = Null")
def last_word(data):
words = get_words(data)
if len(words) != 0:
print(f"Last word = {words[-1]}")
if __name__ == "__main__":
first_word(sentence)
second_word(sentence)
last_word(sentence)
I'm trying to set the scrambled word from the list back to the list I have created, which is from split. I tried reading some of the solutions here and I think it's because you can't change the string in the list?
I'm not really sure correct me if I'm wrong :( . the sentence[i] = temp_word is giving the error. thanks in advance :)
class WordScramble:
def __init__(self):
self.user_input = input("Please give me a sentence: ")
def scramble(self):
# print what was input
print("The user input was: ", self.user_input)
# first scramble is just one word
print(self.user_input[0] + self.user_input[2] + self.user_input[1] + self.user_input[3:])
# reverse two indices
# particularly good to use is to switch the first two
# and the last two
# this only makes sense if you have a world that is longer than 3
# now try to scramble one sentence
sentence = self.user_input.strip().split(" ")
for i, word in enumerate(sentence):
if len(word) > 3:
temp_word = list(word)
if ',' in temp_word:
temp = temp_word[1]
temp_word[1] = temp_word[-3]
temp_word[-3] = temp
else:
temp = temp_word[1]
temp_word[1] = temp_word[2]
temp_word[2] = temp
temp_word = ''.join(temp_word)
sentence[i] = temp_word
sentence = ''.join(sentence)
print(sentence)
#print(" ".join(sentence))
# do just words first, then you can move on to work on
# punctuation
word_scrambler = WordScramble()
word_scrambler.scramble()
Because inside the for loop you wrote:
sentence = ''.join(sentence)
Thus, at the second iteration, the 'sentence' variable is now a string and in python, strings don't support item assignment as they are immutable variables. I think you meant to get this out of the for loop to print the final sentence.
I've got a code that in theory should take an input of DNA that has errors in it and removes all errors (N in my case) and places a count of how many N's were removing in that location.
My code:
class dnaString (str):
def __new__(self,s):
#the inputted DNA sequence is converted as a string in all upper cases
return str.__new__(self,s.upper())
def getN (self):
#returns the count of value of N in the sequence
return self.count("N")
def remove(self):
print(self.replace("N", "{}".format(coolString.getN())))
#asks the user to input a DNA sequence
dna = input("Enter a dna sequence: ")
#takes the inputted DNA sequence, ???
coolString = dnaString(dna)
coolString.remove()
When I input AaNNNNNNGTC I should get AA{6}GTC as the answer, but when I run my code it prints out AA666666GTC because I ended up replacing every error with the count. How do I go about just inputting the count once?
If you want to complete the task without external libraries, you can do it with the following:
def fix_dna(dna_str):
fixed_str = ''
n_count = 0
n_found = False
for i in range(len(dna_str)):
if dna_str[i].upper() == 'N':
if not n_found:
n_found = True
n_count += 1
elif n_found:
fixed_str += '{' + str(n_count) + '}' + dna_str[i]
n_found = False
n_count = 0
elif not n_found:
fixed_str += dna_str[i]
return fixed_str
Not the cleanest solution, but does the job
from itertools import accumulate
s = "AaNNNNNNGTC"
for i in reversed(list(enumerate(accumulate('N'*100, add)))):
s=s.replace(i[1], '{'+str(i[0] + 1)+'}')
s = 'Aa{6}GTC'
That's expected, from the documentation:
Return a copy of string s with all occurrences of substring old replaced by new.
One solution could be using regexes. The re.sub can take a callable that generates the replacement string:
import re
def replace_with_count(x):
return "{%d}" % len(x.group())
test = 'AaNNNNNNGTNNC'
print re.sub('N+', replace_with_count, test)
I have a simple task that I need to do; let's say I have a word, any word. And in that word, I need to find how many instances of a letter there are. And that letter that I'm finding has a value, let's say 5. I then need to multiply how many instances of that letter there are by 5, to accumulate a total score. Sounds simple enough, but I lack the knowledge in order to make it happen. I've begun coding a test, but even that doesn't work. Any help would be appreciated.
def vowel1(Word,x):
x = a
for a in Word:
if a==x:
print ("True")
print ("False")
Word = input("Please enter a word (from the english dictionary) if you please ")
print (Word)
vowel1(Word,x)
I know there are no signs of a variable with value in that, but I don't know how to do it.
So, effectively, scrabble?
A nice simply approach would be to create a dictionary of scores and simply go through the word, looking for values in the dictionary. You can add verification and simplify it, but the general logic could be (assuming python3):
import string
def getScore(word, scoremap):
total = 0
for a in word:
total += scoremap[a.lower()]
return total
word = input("Please enter a word (from the english dictionary) if you please ")
print(word)
scoremap = {}
# generate the scores how you wish, the following is just an example:
for i in string.ascii_lowercase:
scoremap[i] = 1
scoremap['e'] = 5
print(getScore(word,scoremap))
I think you have a small mistake. Remove the second line of your function?
def vowel1(Word,x):
# x = a # This negates the value of x you just entered in the function
for a in Word:
if a==x:
print ("True")
print ("False")
str.count(sub[, start[, end]])
Example:
word = "example"
word.count('e')
On the end you must only multiply by 5
def VowelOne():
var = (Word.count('a')*5)
return var
def VowelTwo():
var = (Word.count('e')*4)
return var
Word = input("Please enter a word (from the english dictionary) if you please ")
var = VowelOne()
VarTwo = VowelTwo()
print (Word)
print(VowelOne()+VowelTwo())
This I have found to be the simplest solution; I just multiplied how many instances of a letter there are by its score. Thanks to all contributions.
I am a python newbie, and am struggling for what I thought was a simple code. My instructions are, Write a function that takes one string parameter word and will return the number of vowels in the string.
Also, just for clarification, supercat is my one string parameter word.
I've been working on this code for some time, and it's gotten a little jumbled.
This is what I have so far.
vowelletters = ["A","E","I","O","U","a","e","i","o","u"]
def isVowel(supercat):
if supercat in vowel:
return True
else:
return False
print isVowel(supercat)
def countvowel(supercat):
count = 0
for index in super cat:
if isVowel(vowelletters): count += 1
return count
y = countvowel(super cat)
print(y)
you can first make the string to test lowercase() so that you don't have to check for capital vowels (this make it more efficient). Next you can count() how many times each vowel is in the teststring and make a final sum() to get a total.
vowelletters = ["a","e","i","o","u"]
teststring= "hellO world foo bAr"
count = sum(teststring.lower().count(v) for v in vowelletters)
print count #6
You can place everything in a function to easily reuse the code.
def countVowels(mystring):
vowelletters = ["a","e","i","o","u"]
return sum(mystring.lower().count(v) for v in vowelletters)
Spaces in variable names not allowed, I would say:
for index in super cat:
and
y = countvowel(super cat)
It looks to me as if your indentation has problems and you left an extra space in there. (super cat instead of supercat)
You also used vowelletters instead of index in countvowel() and forgot to use the global statement in isVowel().
vowelletters = ["A","E","I","O","U","a","e","i","o","u"]
def isVowel(supercat):
global vowelletters
if supercat in vowelletters:
return True
else:
return False
print isVowel(supercat) # This isn't executed
# because it is after a return statement.
def countvowel(supercat):
count = 0
for index in supercat:
if isVowel(index): count += 1
return count
y = countvowel("supercat")
print(y)
how about this:
vowelletters = ("a","e","i","o","u")
def countvowel(word):
word = word.lower()
count = 0
for char in word:
if char in vowelletters:
count += 1
return count
print countvowel('super cat') # prints 3
or using the list comprehension:
vowelletters = ("a","e","i","o","u")
def countvowel(word):
word = word.lower()
vowels = [char for char in word if char in vowelletters]
return len(vowels)
You can simplify this function that you're writing
def countvowel(supercat):
count = 0
for i in range(len(supercat)-1):
if supercat[i] in "AEIOUaeiou":
count += 1
print(count)
You can use sum() and a generator.
def countVowels(word):
return sum(1 for c in word if c in "AEIOUaeiou")
print(countVowels('supercat'))