Python item in list not working - python

I am having an issue with an if statement regarding an item in a list. Here is the code I am using
score = 0
for j in range(0,1):
for k in range(0,len(split)):
keyword = str(split[k][1])
words = texts[j]
print(keyword,words)
if str(keyword) in list(words):
print("true")
score = score + float(split[k][0])
else:
print("false")
print(score)
Here is the portion of the output where the statement is visibly wrong. What is wrong in the situation?
"now" ['anonym', 'now']
false
0

Your keyword is "now" - INCLUDING the quote marks. It indeed does not exist in words, which only includes words without quote marks. Either fix whatever problem with the source of the data is adding those quotes, or strip them off with something like keyword = keyword.strip('"').

Related

Why does the python adds letters in dictionary?

I have been recently trying to make a program in python that makes text cipher but this is what happens :
text='abab'#the text we want to replace
result=''#we are going to replace it
replace_map={'a':'b', # a dictionary map to replace the text
'b':'a'
}
for ch in text: #loop through every text in the loop
if ch in replace_map: # if the text is in the replace map
result += replace_map[ch] #then we are going to replace every letter in it from replace map
else:
result += ch#else just add the value with no changing
print(text)#for comparison
print(result)#then print the text after replacing it
I want the result text to be 'abab' instead of 'babab'.
please help.
Indentation in Python is critical! The interpreter is misunderstanding the flow of the program because the else keyword is not indented properly. Try using an IDE, which generally does well at indenting the code as needed (if and else statements on the same level, etc).
If you indent the code properly, it looks like the following. I have tested this code on my machine and I can confirm it works.
text = 'abab'#the text we want to replace
result = ''#we are going to replace it
replace_map = {
'a':'b', # a dictionary map to replace the text
'b':'a'
}
for ch in text: # loop through every text in the loop
if ch in replace_map: # if the text is in the replace map
result += replace_map[ch] # then we are going to replace every letter in it from replace map
else:
result += ch # else just add the value with no changing
print(text) # for comparison
print(result) # then print the text after replacing it
The problem is that your else statement is out of the for-loop, just add an indent to it, and it should give you your results.

Remove the parentheses

Recently I was solving a problem in Codewars and got stuck. The link of the problem link
Basically what it is asking for is :
You are given a string for example :
"example(unwanted thing)example"
Your task is to remove everything inside the parentheses as well as the parentheses themselves.
The example above would return:
"exampleexample"
Don't worry about other brackets like "[]" and "{}" as these will never appear.
There can be multiple parentheses.
The parentheses can be nested.
Some other test cases are given below :
test.assert_equals(remove_parentheses("hello example (words(more words) here) something"), "hello example something")
test.assert_equals(remove_parentheses("(first group) (second group) (third group)"), " ")
I looked up online and I found some solution involving Regex, but I wanted to solve this problem without Regex.
Till now I have tried similar solutions as given below :
def remove_parentheses(s):
while s.find('(') != -1 or s.find(')') != -1 :
f = s.find('(')
l = s.find(')')
s = s[:f] + s [l+1:]
return s
But when I try to run this snippet, I get Execution Timed Out.
You just need to track the number of open parentheses (the nested depth, technically) to see whether the current character should be included in the output.
def remove_parentheses(s):
parentheses_count = 0
output = ""
for i in s:
if i=="(":
parentheses_count += 1
elif i==")":
parentheses_count -= 1
else:
if parentheses_count == 0:
output += i
return output
print(remove_parentheses("hello example (words(more words) here) something"))
print(remove_parentheses("(first group) (second group) (third group)"))
Use Stack to check whether '(' is closed or not.
If the length of Stack is not zero, that means that parentheses are still open, So you have to ignore the characters.
The code below will pass all the test cases.
def remove_parentheses(s):
stack = []
answer = []
for character in s:
if(character == '('):
stack.append('(')
continue
if(character == ')'):
stack.pop()
continue
if(len(stack) == 0):
answer.append(character)
return "".join(answer)
The reason for your code to have Execution Timed out is because it is stuck in an infinity loop. Since s = s[:f] + s [l+1:] doesn't remove the parentheses properly, such as
a nested example hello example (words(more words) here) something
your code will locate the first ( and the first ) and return hello example here) something on the first loop, which will lead to incorrect result in the next loop as one of your ( is removed.
To be honest, an approach like this is not ideal as it is difficult to understand and read since you have to dry run the index in the loop one by one. You may continue to debug this code and fix the indexing, such as only search the nearest/enclosed closing bracket according to your first located (, which will make it even more harder to read but get the job done.
For me, I would personally suggest you to look up regular expression, or what is often referred as regex,
a very simple algorithm that builds on regex is
import re
def remove_parentheses(s):
s = re.sub("\(.{1,25}\)", "", s)
return s
def f(s):
pairs = []
output = ''
for i, v in enumerate(s):
if "(" == v:
pairs.append(1)
if ")" == v:
pairs.pop()
continue
if len(pairs) ==0:
output +=v
return output
Can be achieved easily if we use a recursive function.. Try this out.
def rmp(st):
if st.find('(') == -1 or st.find(')') == -1: return st
else :
i=st.rindex('(')
j=st[i+1:].index(')')
return rmp(st[:i] + st[i+1+j+1:])
Here are a few cases I tested...
print(rmp("hello example (words(more words) here) something"))
print(rmp("(first group) (second group) (third group)"))
print(rmp("This does(n't) work (so well)"))
print(rmp("(1233)qw()"))
print(rmp("(1(2(3(4(5(6(7(8))))))))abcdqw(hkfjfj)"))
And the results are..
hello example something
This does work
qw
abcdqw

Separate initials from full name input in python without using split

EDIT This was my first post and I completely forgot to show what I had already tried. I wasn't looking for a complete program, just suggestions on methods I could use to concatenate initials. EDIT
I need to create a program that allows a user to input their full name and only prints the initials. This must be done WITHOUT USING .SPLIT OR LISTS
From my hw:
Write a program that gets a string of a person's full name – first, middle, and last name and then displays their initials.
Create a function getInitials().
>>>Enter your full name: James Tiberias Kirk
>>>J.T.K.
Try this one:
n = input('Enter your full name:')
name = ''
for i,j in enumerate(n):
if i == 0:
name+=(j+'.')
elif j == ' ':
name += (n[i+1]+'.')
print(name)
And this is as method:
def getinitials(n):
name = ''
for i,j in enumerate(n):
if i == 0:
name+=(j+'.')
elif j == ' ':
name += (n[i+1]+'.')
return name
print(getinitials(input('Enter your number:')))
Output:
Enter your full name:James Tiberias Kirk
J.T.K.
I ended up figuring it out thanks to all your responses. Our teacher wanted us to only use the narrow scope of what we've learned in class so there was pretty much only one way I would be allowed to write it. I ended up coming up with this:
def getInitials():
fullName=input("Enter your full name:")
initials=''
for ch in fullName:
if ch.isupper():
initials+=ch
initials=str(initials)+"."
print (initials)
if __name__=="__getInitials__":
getInitials()
getInitials()
Assuming you won't deal with names like DeFranco or McDonald, you can iterate over the string and append encountered capital letters (that is, ord('A') <= ord(char) <= ord('Z')) with a dot to your result.
Similar approach that should work on most cases is to append the first character, then look for spaces and append a character next to them.
One solution that technically doesn't use a list:
'.'.join(i for i in x if i.isupper())+'.'
...which uses a generator expression, but that may be closer to a list than the spirit of the assignment. As in the other answer, it fails if a name has more than one capital in the name (McGregor, etc.)
You could use a regex, while returning a generator statement from your getInitials() function, therefore you technically avoid using both split() and a list:
import re
def getInitials(x):
return '.'.join(i for i in re.findall(r'^[A-Z]|(?<=\s)[A-Z]', x)) + '.'
out = getInitials('James Tiberias Kirk McGregor')
Yields:
J.T.K.M.
Note that this method works for names with more than one capital letter per name/word.

Python Split a string by diffrent . full stops

hey i want to be able to change my string being split at say the third full stop or the 2nd here is my code
file = "hey there. this is some demo code. will you nice people please help me."
i want to split the string after the 2nd full stop so it will look like
"hey there. this is some demo code."
".".join(file.split(".")[2:])
or
file.split(".",2)[2:]
These use str.split() (2/3), str.join() (2/3), and slices (2/3). There's no reason to use loops or regex for this.
I would do something like this:
readf = open("split.txt")
for line in readf:
a=line.split(".")
readf.close()
print (a[:2])
Basically you store the line in a and split it on "." and then use a subsequence which you can use however you like.
e.g. a[2:3] gives u the secound and third line while a[:3] gives you all three.
A rough way to do it would be to use a counter and loop through the string, adding every character until the stopping limit is reached.
firstString = ""
secondString = ""
stopsAllowed = 1
stopsFound = 0
for i in range(0,len(file)):
if file[i] == ".":
stopsFound += 1
if stopsFound <= stopsAllowed:
firstString += file[i]
else:
secondString += file[i]

Procedure in Python

Question
Write a procedure that takes a string of words separated by spaces (assume no punctuation or capitalization), together with a ”target” word, and shows the position of the target word in the string of words. For example, if the string is:
'we dont need no education we dont need no thought control no we dont'
and the target is the word ”dont” then your procedure should return the list 1, 6, 13 because ”dont” appears at the 1st, 6th, and 13th position in the string. (We start counting positions of words in the string from 0.) Your procedure should return False if the target word doesn’t appear in the string.
My solution-
def procedure(string,target):
words=string.split(" ") #turn the string into a list of words
solution=[] #list that will be displayed
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
return solution
string="we dont need no education we dont need no thought control no we dont"
print procedure(string, "dont")
assert procedure(string, "dont")
Why is this not running in python?! The problem is on print procedure(string, "dont") it mentions invalid syntax. I am running it in the IDLE.
The following is your code with the indentation fixed, compare this with what you posted and you should see why it now works.
It is unclear to me why your original code has a problem because the indentation controls how python views the blocks of code and will fail to run if the indentation is incorrect. I suspect that your problem is that you had these lines in your code:
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
The above will fail and return False because solution length will be 0 on the first iteration if your word is not found on the first iteration, you should check the len of solution outside the scope of the for loop.
In [42]:
def procedure(string,target):
words=string.split(" ") #turn the string into a list of words
solution=[] #list that will be displayed
for i in range(len(words)):
if words[i]==target: solution.append(i)
if len(solution)==0: return False
return solution
string="we dont need no education we dont need no thought control no we dont"
print(procedure(string, "dont"))
assert(procedure(string, "dont"))
[1, 6, 13]
You can user a list comprehension for this:
def list_word_indexes(word, text):
return [index for index, text_word in enumerate(text.split())
if text_word == word]
The problem is on print procedure(string, "dont") it mentions invalid syntax
This means you are using python 3, where print is a function and not a statement. You should add brackets around the argument(s) to print or make sure to use python 2.
eg.
print(procedure(string, "dont"))

Categories

Resources