I have a Problem, I have to solve a task in Python and I dont know how to do it. The task is to define a function number_of_vowels, where the output should be the Number of vowels in a Word. With this function I have to write anotherone, many_vowels thats working with a list an a Number and where the number says how many vowels have to be at least in a word to be appended to the result list and then I have to append this Word. Thanks to everybody helping me ;D.
here is the code:
Wort = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
while result < 20:
if Word[counter0] == 'a' or 'e' or 'i' or 'o' or 'u':
result = result + 1
counter0 = counter0 + 1
else:
counter0 = counter0 + 1
return result
Words = []
counter1 = 0
def many_vowels(List , number):
if number_of_vowels(List[counter1]) < number:
counter1 + 1
else:
Words.append(List[counter1])
counter1 + 1
return Words
This code just gives me the answer to the letter a and not to the other vowels. For
print(number_of_vowels(Wort))
the output is: 1
but there are 4 vowels in this word
it also says: line 21, in many_vowels
IndexError: string index out of range
You're trying to call a function with wrong brackets. Function call should use round ones.
Try changing number_of_vowels[List[counter1]] with number_of_vowels(List[counter1])
This code contains some errors:
Calling for function should be using round brackets: number_of_vowels(List[counter1]) instead of number_of_vowels[List[counter1]]
doing result + 1 won't change value of the variable result, since you did not put the calculation result in the variable. use result = result + 1 (same for counters)
in number_of_vowels function, you want to scan the whole word? cause you did not use any loop, so it currently looking only at the first letter. Secondly, you put the compression in result and then add 1 to it. I'm not really sure why
edit:
Word = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
for index, letter in enumerate(Word):
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
result = result + 1
return result
Words = []
counter1 = 0
def many_vowels(List_name , number):
for index, item in enumerate (List_name):
if number_of_vowels(item) >= number:
Words.append(item)
return Words
Related
I have been working on the python challenge question and I have been stuck it on for a while. Below is the question.
Write a function that takes a string and calculates the number of letters and digits within it. Return the result in a dictionary.
Examples:
count_all("Hello World") ➞ { "LETTERS": 10, "DIGITS": 0 }
count_all("H3ll0 Wor1d") ➞ { "LETTERS": 7, "DIGITS": 3 }
count_all("149990") ➞ { "LETTERS": 0, "DIGITS": 6 }
Notes:
Tests contain only alphanumeric characters.
Spaces are not letters.
All tests contain valid strings.
The function should return dictionary
I have written a code to solve it but I have been getting a 'Too many positional arguments for function call.
def count_all(string):
d = 0
l = 0
for c in string:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print(count_all("string", "l"))
print(count_all("string", "d"))
what have I done wrong exactly?
Pretty much all you need to do is make it so that you're passing just 1 string to your function, like so: print(count_all("letters and numbers 12345")). And second, you need to change the output so that it should return a dict, like so: return {"letters": l, "digits": d}.
Try this out
def countStuff(argString = None):
resultDict = {"Letters" : 0, "Numbers" : 0}
if argString is None:
print("-_-")
for i in argString:
if i.isdigit():
resultDict["Numbers"] += 1
elif i.lower().islower():
resultDict["Letters"] += 1
else:
pass
print(resultDict)
alphacount = 0
numcount = 0
str1 = input("Enter a sentence: ")
for x in str1:
if x.isalpha(): # Check the Albhabets in String
alphacount+=1
elif x.isdigit(): # Check the digits in String
numcount+=1
else:
continue
print('LETTERS '+ str(alphacount))
print('DIGITS '+ str(numcount))
I want to find the number of occurrences of a particular sub-string in a string.
string="abcbcbcb"
sub_str="cbc"
c=string.count(sub_str)
print(c)
This gives the output as
1
which is the number of non-overlapping occurrences of substring in the string.
But I want to calculate the overlapping strings as well. Thus, the desired output is:
2
You can use a regular expression, use module "re"
print len(re.findall('(?=cbc)','abcbcbcb'))
No standard function available for overlapping count. You could write custom function tho.
def count_occ(string, substr):
cnt = 0
pos = 0
while(True):
pos = string.find(substr , pos)
if pos > -1:
cnt += 1
pos += 1
else:
break
return cnt
string="abcbcbcb"
sub_str="cbc"
print(count_occ(string,sub_str))
The first occurrence of the character in the string will be replaced with a 1, the second occurrence with a 2, etc.
ive tried using for loop and the max function to replace the last occurence but it doesnt seem to work.
string=str(input('string: '))
x=input('character: ')
list=[]
for i in range(len(string)):
if string[i]==x:
list.append(i)
Z=str(max(list))
print(string.replace(x,Z,[::-1]))
the output should be as following
string: departmentofcomputerscience
character: e
d1partm2ntofcomput3rsci4nc5
Here's a way to do it.
Use a counter for each character in the loop, and store values in the list, then merge the list. Use the current value if not equal to the character, counter otherwise:
string=str(input('string: '))
x=input('character: ')
# Use list to store results and a counter
l = []
counter = 0
for c in string:
if c==x:
counter += 1
l.append(str(counter))
else:
l.append(c)
# Merge the resulting list into string
res = "".join(l)
# Output the result
print(res)
For the input string: departmentofcomputerscience
and the character: e
The output is
d1partm2ntofcomput3rsci4nc5
Here is another way to achieve the goal using a list and the method replace():
string = str(input('string: '))
x = input('character: ')
list = []
for i in range(len(string)):
if string[i] == x:
list.append(i) # add all indexes to replace to the list
if len(list) > 0:
j = 0
for i in range(len(list)):
j += 1
string = string.replace(string[list[i]], str(j), 1) # replace the element once at time
print(string)
For string: departmentofcomputerscience
character: e
Output: d1partm2ntofcomput3rsci4nc5
def replace(s, c):
'''
#parameter s: input string
#parameter c: input character to be replaced
#return s: where every occurence of c is
replaced by it's nth occurence
'''
so = list(s)
j = 1
for i in range(len(so)):
if so[i] == c:
so[i] = str(j)
j = j + 1
return ''.join(so)
How to count sub-strings in a string?
Example: findSubstrings("foxcatfox","fox") # should return 2
If recursion is really a must, you can try dividing the problem first.
Say if you found a matching substring at position i, then the total number of substring is 1 + findSub(string[i+1:], sub), so you can write something like this:
def findSubstringsRecursive(string, substring):
counter = 0
substringLength = len(substring)
for i in range(len(string)):
if string[i] == substring[0]:
end = i + substringLength
sub1 = string[i:end]
if substring == sub1:
return 1 + findSubstringsRecursive(string[i+1:], substring)
return 0
The following pure recursive approach is simple enough (apart from the bool->int coercion):
def findRec(s, pat):
if len(s) < len(pat): # base case should be obvious
return 0
return (pat == s[:len(pat)]) + findRec(s[1:], pat) # recurse with smaller size
>>> findSubstrings('foxcatfox', 'fox')
2
>>> findSubstrings('foxcatfox', 'foxc')
1
>>> findSubstrings('foxcat', 'dog')
0
I should note that this counts overlapping occurrences which may or may not be desired. One might also add protection against or define behaviour for an empty substring.
I'm working on a small program which takes a text input - and then places each of these items in a dictionary alongside which line they were entered on. At the moment if I enter 4 lines of text. It'll take them all out correctly, but every word will be set to the value 4 - instead of the loop it was inputted on. I've removed all the other functions from my code (remove punct, remove stopwords, stemwords, etc). to make this clearer.
from string import *
function = False
words_split = []
lineNumber=0
final_value = []
def indexer(t):
global words_split
words = t.split();
for word in words:
words_split.append(word)
def dict_print():
for keys in Dict:
output = keys + " " + str(Dict[keys][0])
i= 1
while i < len(Dict[keys]):
output = output + ", " + str(Dict[keys][i])
i = i + 1
print(output)
print("Please type a line and hit 'Enter' or type a single fullstop followed by 'Enter' to exit \n")
text = ""
while function == False :
if(text == "."):
print("The index is:")
function = True
dict_print()
else:
Dict = {}
text = input()
lineNumber += 1
for word in words_split:
if word in Dict:
if lineNumber not in Dict[word]:
Dict[word] = Dict[word] + [lineNumber]
else:
Dict[word] = [lineNumber]
indexer(text)
My global variable was causing the issue. I'll leave this up with my completed full code in case someone else runs into the same issue (:
https://repl.it/#Glaschu/AdmiredSteelCardinal