Writing a function to see how many times a character appears in a set of words - python-3.x

To better help understand the fundamentals, my professor asked people in our class to write a function to see how many times a character appears in a set of words. I am having trouble integrating ord() into the function. Also, I understand that there are easier ways of getting the outcome.
Here is what I have so far:
def function(char):
word = "yes"
for char in word:
ord(char)
return ord(char)
function('y')
I don't get any errors - but I also don't get anything back

That is because you aren't printing anything!
Also, there are issues in your code, first one being the parameter 'char' and the 'char' in the for loop have the same name, that will cause issues.
A small code to find the count of a given letter can be something like this:
def function(word, char):
count = 0
for c in word:
if c == char:
count = count + 1
return count
print (function("yes", 'y'))

return will automatically end a function, and not keep it going.
there are also a lot of variables that you are not using, like the char parameter you passed to your function. when using the for loop, the variable created after for will be reassigned.
try this:
def function():
word = 'yes'
NewList = []
for char in word:
NewList.append(ord(char))
return NewList
print(function())
however what i think would be better:
def function(word):
NewList = []
for char in word:
NewList.append(ord(char))
return NewList
print(function('blahblah'))
also, when simply calling a function from a file, the returned value is not automatically displayed, you must include a call to print

Related

Index out of range in leetcode ide in code for finding the length of the longest substring without repeating characters

This below giving expected output in pycharm and the other side it's getting index out of range in line return length_of_substring[-1] in leetcode.
why it is getting such error?
class Solution:
def lengthOfLongestSubstring(self, string):
unique_list = []
length_of_substring = []
for i in string:
if i not in unique_list:
unique_list.append(i)
else:
length_of_substring.append(len(unique_list))
unique_list.clear()
unique_list.append(i)
length_of_substring.sort()
return length_of_substring[-1]
if __name__ == '__main__':
s = input()
obj = Solution()
result = Solution.lengthOfLongestSubstring(obj, s)
print(result)
First of all: when posting here you should clearly specify (i) the goal of your code and (ii) a self contained minimum example.
In your case it is very difficult to answer your question, because you do not make clear what your code is actually trying to achieve.
Regarding your error message:
Your code does not account for the fact that a string could also consist of only unique elements (e.g. "abcd"). In that case the else clause of your code is never reached and length_of_substring will remain empty. If you then call length_of_substring[-1] it raises an error message.

How to remove marks from string and turn it into a list

I need to create a function that turns the string to a list without !?., %#$ . and without capital letters. The string at the end is just an example so it needs to return ['mr', 'stark', 'i', "don't", 'feel', 'so', 'good']
Can someone tell me why my code prints None?
def sentence_to_words(s):
# Write the rest of the code for question 2 below here.
s_new= []
s1 = s.split()
a = ['#',',','!','.','?','$']
for i in s.split():
if i in a:
s2 = s1.remove(i)
s_new = s_new.append(s2)
return s_new
print sentence_to_words("Mr. Stark... I don't feel so good")
The best way to debug this is to validate that your assumptions about program state hold on each step. Don't jump ahead until you're sure each line of code does what you expect. Adding a print inside your loop shows exactly what i is on each iteration:
Mr.
Stark...
I
don't
feel
so
good
None of these words are in a = ['#',',','!','.','?','$'], so the conditional block inside your loop never runs. After the loop is exhausted, your program returns None which Python functions return when no return value is specified.
Furthermore, your conditional block operations aren't working as you expect; check return values and avoid making assignments if they're an in-place operation such as .append(), which returns None and should not be assigned to anything. Also, if the if block does execute, it'll prematurely return the result without finishing work on the rest of the list.
You may be looking for something like this:
def sentence_to_words(s):
s_new = []
ignore = ["#", "!", ",", ".", "?", "$"]
for word in s.split():
cleaned_word = ""
for letter in list(word):
if letter not in ignore:
cleaned_word += letter
s_new.append(cleaned_word.lower())
return s_new
print sentence_to_words("Mr. Stark... I don't feel so good")
Output:
['mr', 'stark', 'i', "don't", 'feel', 'so', 'good']
The approach in the above example is to iterate over words, then iterate over letters in each word to clean them according to the requirements and add the clean word to the result array. Note the descriptive variable names, which aid in understanding the program (for example, i was actually a word in your code, but i usually means integer or index).
The above example can be optimized--it uses a lot of error-prone arrays and loops, the ignore list should be a parameter to make the function reusable, and the in operator is slow on lists (ignore should be a set). Using regex makes it a one-liner:
import re
def sentence_to_words(s):
return re.sub(r"[\#\,\!\.\?\$]", "", s).lower().split()
Or using filter and the list of characters to ignore as a default parameter:
def sentence_to_words(s, ignore=set("#!,.?$")):
return filter(lambda x: x not in ignore, s).lower().split()
Try it!
I couldn't understand your code very well, but where's an alternative using re.sub and split().
We first remove any special chars with re.sub an then use split to get a list of words, i.e.:
import re
sentence = "Mr. Stark... I don't feel so good"
words = re.sub(r"[#,!\?\$.]", "", s).split()
Using re.split:
words = re.split("[^a-z'-]+", sentence, 0, re.IGNORECASE)
Both examples output:
# ['Mr', 'Stark', 'I', 'don't', 'feel', 'so', 'good']
Ideone Demo

Find a repeated character in a string (python)

I managed to find this code online which showed me how to find and print a repeated character in a string. I'm confused as to how it's working though. I don't understand what the h[i] = 0 part is technically doing. Can someone please explain?
a = 'abcdeab'
h = {}
for i in a:
if i in h:
print(i)
else:
h[i] = 0
I understand how it's iterating over the string, but I don't understand how it's being added to the dictionary in order to be checked if it already exists in that dictionary or not. Setting h[i] = 0 is what's throwing me off. I don't understand why it's being set to 0.
I'm adding this after the problem was answered:
I ended up creating a different solution and thought I would post it in case anyone else was looking into the same problem. It is as follows (using a list instead of a dictionary):
a = 'abcdeab'
h = []
for i in a:
if i in h:
print(i)
else:
h.append(i)
Also, if you're looking for ONLY the first occurrence of a repeated character, you would add break after print(i). In this case, it would only print a instead of both a and b.
The variable h has been defined to be a dictionary. For each letter in your input string, if it be present in the map, it gets printed, otherwise the map gets assigned a (key, value) pair of (letter, 0). That is, an entry is made into the map with the letter as the key, and zero as the (arbitrary) value. Here is your loop with some comments:
for i in a:
if i in h: # if the key 'i' exists in the dictionary
print(i)
else:
h[i] = 0 # otherwise add an entry for this letter

How to count number of substrings in python, if substrings overlap?

The count() function returns the number of times a substring occurs in a string, but it fails in case of overlapping strings.
Let's say my input is:
^_^_^-_-
I want to find how many times ^_^ occurs in the string.
mystr=input()
happy=mystr.count('^_^')
sad=mystr.count('-_-')
print(happy)
print(sad)
Output is:
1
1
I am expecting:
2
1
How can I achieve the desired result?
New Version
You can solve this problem without writing any explicit loops using regex. As #abhijith-pk's answer cleverly suggests, you can search for the first character only, with the remainder being placed in a positive lookahead, which will allow you to make the match with overlaps:
def count_overlapping(string, pattern):
regex = '{}(?={})'.format(re.escape(pattern[:1]), re.escape(pattern[1:]))
# Consume iterator, get count with minimal memory usage
return sum(1 for _ in re.finditer(regex, string))
[IDEOne Link]
Using [:1] and [1:] for the indices allows the function to handle the empty string without special processing, while using [0] and [1:] for the indices would not.
Old Version
You can always write your own routine using the fact that str.find allows you to specify a starting index. This routine will not be very efficient, but it should work:
def count_overlapping(string, pattern):
count = 0
start = -1
while True:
start = string.find(pattern, start + 1)
if start < 0:
return count
count += 1
[IDEOne Link]
Usage
Both versions return identical results. A sample usage would be:
>>> mystr = '^_^_^-_-'
>>> count_overlapping(mystr, '^_^')
2
>>> count_overlapping(mystr, '-_-')
1
>>> count_overlapping(mystr, '')
9
>>> count_overlapping(mystr, 'x')
0
Notice that the empty string is found len(mystr) + 1 times. I consider this to be intuitively correct because it is effectively between and around every character.
you can use regex for a quick and dirty solution :
import re
mystr='^_^_^-_-'
print(len(re.findall('\^(?=_\^)',mystr)))
You need something like this
def count_substr(string,substr):
n=len(substr)
count=0
for i in range(len(string)-len(substr)+1):
if(string[i:i+len(substr)] == substr):
count+=1
return count
mystr=input()
print(count_substr(mystr,'121'))
Input: 12121990
Output: 2

Index out of range - Python

I was programming at CodeWars using Kata, when i got this error:
Traceback:
in
in title_case
IndexError: list index out of range
Here is my code:
def title_case(title, minor_words=1):
string = title.split()
outList = []
if minor_words != 1:
split = minor_words.split()
minor = [x.lower() for x in split]
out = ""
for i in range(0, len(string)):
word = ""
for j in range(0,len(string[i])):
elem = ""
elem += string[i][j]
if j == 0:
word += elem.upper()
else:
word += elem.lower()
if i != len(string)-1:
outList.append(word+" ")
else:
outList.append(word)
list = [x.lower() for x in outList]
print ((list[0]))#Just for debug
if minor_words != 1:
for i in range(0, len(outList)):
if (list[i] in minor):
print("OI")#Just for debug
out += list[i]
else:
out += outList[i]
return out
Well, this happened when trying to execute the code, of course!
One way to initialize this function would be:
title_case('a clash of KINGS', 'a an the of')
Well the 0 elemeny exists, but it says it doesn't, I don't know why, because when I write "print(list)" it shows me the elements of list, in this case, "['a', 'clash', 'of', 'kings']".
What can I do?
Okay, so based on reading this code I think the result you desire from:
title_case('a clash of KINGS', 'a an the of') is:
A Clash of Kings
So it looks like you are stepping through a lot of hoops trying to get there. While I was going through the code it took me a while to see what was actually happening. I also took the liberty to make your variables more consistently named. Rather than mixing caseLetter and case_letter randomly I made it consistent. I also made your loops easier to read. Also for the minorWords argument. Might as well have it passed as a list rather than converting it to a list inside the function. Anyway, I hope this is of help.
def titleCase(title, minorWords=[]):
titleList = [x.lower() for x in title.split()]
outList = []
for Word in titleList:
if Word not in minorWords:
Word = Word.capitalize()
outList.append(Word)
return " ".join(outList)
TitleCased = titleCase("a clash of KINGS", ["an", "the", "of"])
print (TitleCased)
Which outputs A Clash of Kings, which I believe, based on your question and how I understood your code is what you wanted to achieve? Or if you include a in your minorWords, it would be:
a Clash of Kings
Regardless, hope this answers your question!

Resources