Index out of range - Python - python-3.x

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!

Related

how can i print the right value in the code?

I'm new to python, and I'm having trouble resolving this code. I just have to print the position of the string when j equals r. But it prints nothing.
class List():
def __init__(self, l_red, l_erd, r):
self.l_red = "ABCEFGC"
self.l_erd = "DBFEGAC"
self.r = l_red[0]
def posicao(self):
j = self.l_red[0];
while self.l_erd[j] != self.r:
j = j + 1
print(j)
This is a bit hard to understand but I will give it a go.
To begin with you really need to consider using a different name for the class; List is already in python.
To instantiate and use this class you would need to use:
a_variable = List() # or whatever you are going to use
a_variable.posicao()
l_red is a string which can act like a character list, and l_erd is the same. Lists take an integer number (0, 1, 2, 3 ...) and return what was in that place. So what you need to do is something more like:
def posicao(self):
letter_of_interest = "A"
j = 0
for j in range(0, len(self.l_erd):
if letter_of_interest == self.r:
print(j)
break
Now what I have written is just for a single character, and you would use a loop to go through each character of interest, but I will leave that to you.
If you want it to find all the positions where that character exists just remove that break.
There are better methods of doing this, look into just using "ABCDE".index('A') this works.

How to compare an input() with a variable(list)

(Im using python on Jupiter Notebook 5.7.8)
I have a project in which are 3 lists, and a list(list_of_lists) that refer to those 3.
I want my program to receive an input, compare this input to the content of my "list_of_lists" and if find a match I want to store the match in another variable for later use.
Im just learning, so here is the code I wrote:
first = ["item1", "item2","item3"]
second = ["item4","item5","item6"]
list1 = [first,second]
list2 = ["asd","asd","asd"]
list_of_lists = [list1,list2]
x = input("Which list are you going to use?: ")
for item in list_of_lists:
if item == x:
match = item
print(match)
print('There was a match')
else:
print('didnt match')
I expect a match but it always output "the didnt match",
I assume it fail to compare the contect of the input with the list inside the list_of lists. The question is also why and how to do it properly(if possible), thanks.
input in python3 returns a string. if you want to convert it into a list, use ast.literal_eval or json.loads or your own parsing method.
list_str = input("Which list are you going to use?: ")
user_list = ast.literal_eval(list_str)
assert isinstance(user_list, list)
...
# do your thing...
So here i tried this code, and it does what i desire, I dont know if its too rudimentary and if there is another way to achieve this.
Here I use a second list to catch the moment when there is a match, after I give to that list the value of my true list and from there print it to be used.
I was wondering if there is a way to take out of the ressults the symbols "[]" and the quotes '', so I can have a clean text format, thanks for the help
first = ["item1", "item2","item3"]
second = ["item4","item5","item6"]
list1 = [first,second]
list2 = ["asd","asd","asd"]
list3 = ["qwe","qwe","qwe"]
list_of_lists = [list1,list2,list3]
reference_list = ["list1","list2","list3"]
count = -1
x = input('Which list are you going to use? ')
for item in reference_list:
count += 1
if x == item:
reference_list = list_of_lists
print(reference_list[count])

Writing a function to see how many times a character appears in a set of words

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

Python 3.xx - Deleting consecutive numbers/letters from a string

I actually need help evaluating what is going on with the code which I wrote.
It is meant to function like this:
input: remove_duple('WubbaLubbaDubDub')
output: 'WubaLubaDubDub'
another example:
input: remove_duple('aabbccdd')
output: 'abcd'
I am still a beginner and I would like to know both what is wrong with my code and an easier way to do it. (There are some lines in the code which were part of my efforts to visualize what was happening and debug it)
def remove_duple(string):
to_test = list(string)
print (to_test)
icount = 0
dcount = icount + 1
for char in to_test:
if to_test[icount] == to_test[dcount]:
del to_test[dcount]
print ('duplicate deleted')
print (to_test)
icount += 1
elif to_test[icount] != to_test[dcount]:
print ('no duplicated deleted')
print (to_test)
icount += 1
print ("".join(to_test))
Don't modify a list (e.g. del to_test[dcount]) that you are iterating over. Your iterator will get screwed up. The appropriate way to deal with this would be to create a new list with only the values you want.
A fix for your code could look like:
In []:
def remove_duple(s):
new_list = []
for i in range(len(s)-1): # one less than length to avoid IndexError
if s[i] != s[i+1]:
new_list.append(s[i])
if s: # handle passing in an empty string
new_list.append(s[-1]) # need to add the last character
return "".join(new_list) # return it (print it outside the function)
remove_duple('WubbaLubbaDubDub')
Out[]:
WubaLubaDubDub
As you are looking to step through the string, sliding 2 characters at a time, you can do that simply by ziping the string with itself shifted one, and adding the first character if the 2 characters are not equal, e.g.:
In []:
import itertools as it
def remove_duple(s):
return ''.join(x for x, y in it.zip_longest(s, s[1:]) if x != y)
remove_duple('WubbaLubbaDubDub')
Out[]:
'WubaLubaDubDub'
In []:
remove_duple('aabbccdd')
Out[]:
'abcd'
Note: you need itertools.zip_longest() or you will drop the last character. The default fillvalue of None is fine for a string.

Common values in a Python dictionary

I'm trying to write a code that will return common values from a dictionary based on a list of words.
Example:
inp = ['here','now']
dict = {'here':{1,2,3}, 'now':{2,3}, 'stop':{1, 3}}
for val in inp.intersection(D):
lst = D[val]
print(sorted(lst))
output: [2, 3]
The input inp may contain any one or all of the above words, and I want to know what values they have in common. I just cannot seem to figure out how to do that. Please, any help would be appreciated.
The easiest way to do this is to just count them all, and then make a dict of the values that are equal to the number of sets you intersected.
To accomplish the first part, we do something like this:
answer = {}
for word in inp:
for itm in word:
if itm in answer:
answer[itm] += 1
else:
answer[itm] = 1
To accomplish the second part, we just have to iterate over answer and build an array like so:
answerArr = []
for i in answer:
if (answer[i] == len(inp)):
answerArr.append(i)
i'm not certain that i understood your question perfectly but i think this is what you meant albeit in a very simple way:
inp = ['here','now']
dict = {'here':{1,2,3}, 'now':{2,3}, 'stop':{1, 3}}
output = []
for item in inp:
output.append(dict[item])
for item in output:
occurances = output.count(item)
if occurances <= 1:
output.remove(item)
print(output)
This should output the items from the dict which occurs in more than one input. If you want it to be common for all of the inputs just change the <= 1 to be the number of inputs given.

Resources