I know this is relatively a basic question. I am trying to verify if given two sentences are synonym based on the given dictionary.
For example if dictionary is [(movie, film), (john, jack)] then "john likes movie" and "jack likes film" are synonym thus the function below will return true.
I changed each of two strings into the list of words by using lower/strip/split, then I tried to compare both lists by using for and if condition. I can't figure out where I did wrong.
def synonym_checker(synonyms, sentences):
a=sentences[0][0]
b=sentences[0][1]
a.lower()
b.lower()
a.strip()
b.strip()
aw=a.split()
bw=b.split()
import string
at = a.maketrans('','',string.punctuation)
bt = b.maketrans('','',string.punctuation)
ase = [w.translate(at) for w in aw]
bs = [w.translate(bt) for w in bw]
dictionary = dict(synonyms)
this = True
for i in range(0, min(len(ase), len(bs))):
if ase[i] != bs[i]:
if (bs[i] != dictionary[ase[i]]) and bs[i] not in [first for first, second in dictionary.items() if second == ase[i]]:
this = False
if (len(ase) != len(bs)):
this = False
is_synonym = this
print(ase)
print(bs)
return is_synonym # boolean
a = [("film", "movie"), ("revadfsdfs", "ads")]
b = [("I really want to watch that movie, as it had good fdf.", "I really want to watch that film, as it had good fdsaa")]
print(synonym_checker(a, b))
So, your error happened on
dictionary[ase[i]]
Because what you did here is actually
{'film': 'movie', 'revadfsdfs': 'ads'}['movie']
When your "movie" is not a key, but a value.
{'film': 'movie', 'revadfsdfs': 'ads'}
.. ^......... ^.............. ^ ............ ^
key .....value ....... key ....... value
The true problem here in my opinion is, your approach is not correct. Because dictionary is a one-way information, so when you want to check both 'film' to 'movie' and 'movie' to 'film', don't use a dictionary.
It also looks like you are trying to do something unnecessarily complicated for what you are trying to achieve.
a.lower()
b.lower()
a.strip()
b.strip()
Does not do anything to the actual program
The way you named your variables are also very hard to read, so maybe pick a proper name instead.
Related
I am fairly new at python (and programming in general, just started 2 months ago). I have been tasked with creating a program that takes a users starting string (i.e. "11001100") and prints each generation based off a set of rules. It then stops when it repeats the users starting string. However, I am clueless as to where to even begin. I vaguely understand the concept of cellular automata and therefore am at a loss as to how to implement it into a script.
Ideally, it would take the users input string "11001100" (gen0) and looks at the rule set I created and converts it so "11001100" would be "00110011" (gen1) and then converts it again to (gen3) and again to (gen4) until it is back to the original input the user provided (gen0). My rule set is below:
print("What is your starting string?")
SS = input()
gen = [SS]
while 1:
for i in range(len(SS)):
if gen[-1] in gen[:-2]:
break
for g in gen:
print(g)
newstate = {
#this is used to convert the string. we break up the users string into threes. i.e if user enters 11001100, we start with the left most digit "1" and look at its neighbors (x-1 and x+1) or in this case "0" and "1". Using these three numbers we compare it to the chart below:
'000': 1 ,
'001': 1 ,
'010': 0 ,
'011': 0 ,
'100': 1 ,
'101': 1 ,
'110': 0 ,
'111': 0 ,
}
I would greatly appreciate any help or further explanation/dummy proof explanation of how to get this working.
Assuming that newstate is a valid dict where the key/value pairs correspond with your state replacement (if you want 100 to convert to 011, newstate would have newstate['100'] == '011'), you can do list comprehensions on split strings:
changed = ''.join(newstate[c] for c in prev)
where prev is your previous state string. IE:
>>> newstate = {'1':'0','0':'1'}
>>> ''.join(newstate[c] for c in '0100101')
'1011010'
you can then use this list comp to change a string itself by calling itself in the list comprehension:
>>> changed = '1010101'
>>> changed = ''.join(newstate[c] for c in changed)
>>> changed
'0101010'
you have the basic flow down in your original code, you jsut need to refine it. The psuedo code would look something like:
newstate = dict with key\value mapping pairs
original = input
changed = original->after changing
while changed != original:
changed = changed->after changing
print changed
The easiest way to do this would be with the re.sub() method in the python regex module, re.
import re
def replace_rule(string, new, pattern):
return re.sub(pattern, new, string)
def replace_example(string):
pattern = r"100"
replace_with = "1"
return re.sub(pattern, replace_with, string)
replace_example("1009")
=> '19'
replace_example("1009100")
=> '191'
Regex is a way to match strings to certain regular patterns, and do certain operations on them, like sub, which finds and replaces patterns in strings. Here is a link: https://docs.python.org/3/library/re.html
I'm running in to a problem with my code. What needs to happen is:
Program asks what your movie channel name is,
Program asks what the code is that you received,
Program checks whether the code you received matches the movie channel you specified,
Program returns a print statement based on the result. If the code was found, print "Match", otherwise print "not found"
The code I have so far is:
def code_controle():
moviechannel = input("What is the name of your movie channel?")
code = input("What is the code you want to check?")
list = [
["RTL8", "20:30", "Rush", "John", "Smith", "123"],
["Veronica", "15:00", "V for Vendetta", "Jane", "Smith" , "ABC"]
]
Now what I need to do is match the moviechannel with a code.
Basically, if I put in "RTL8" and the code "123" it should look through all the lists starting with RTL8, then check the code I put in, with the code in the list. If this matches each other, print "match".
A simple solution is to iterate over the main list and check if the movie and code both exist in any sublist.
Python allows for checking values in a list using in. It is simply if 'value' in list
Writing a method as the one below could be useful if you want to call it often.
for sublist in list:
if movie in sublist and code in sublist:
return True
return False
Edit:
The above code will return true even if the movie and code values are interchanged. If the code is an unique identifier it should be fine, as no movie title would match it.
Since the list is generated by reading from an .csv file, and we are assured that the movie will always be the first item and the code the sixth, we can use the below code for exactly matching only those values.
for sublist in list:
if (movie == sublist[0]) and (code == sublist[5]):
return True
return False
I would wrap that in a try/except to catch any Index out of range just to be safe.
You could tackle that using python dictionaries, but to continue with your example:
found=0
for x in list: #note, change this, list is a type def
if x[0]==code and x[-1]==channel:
found+=1
print "Match"
if (found==0):
print "No match"
I'm assuming this is what you mean:
for line in list:
if moviechannel in line and code in line:
print('Match')
return
print('not found')
Btw you really should reconsider renaming your list, since that is also a built in function.
try this:
>>> my_list = set([moviechannel] + [code])
>>> for x in list:
... if len(set(x) & my_list) == 2:
... print "Match"
...
Match
This is an other way to do it:
new_list = c_list[0] + c_list[1]
if code in new_list and moviechannel in new_list:
print 'Match'
else:
print 'Not found'
You should not use list as list is a built-in function so I changed it to c_list.
I have the following dictionary:
In [32]: mydict
Out[32]:
{'Foo': {'DendriticCells': {'LV.ip': [15.14,1.003],
'SP.ip': [16.0282,3.001]},
'Macrophages': {'LV.ip': [32.137260000000005],
'SP.ip': [34.020810000000004]},
'NKCells': {'LV.ip': [4.89852], 'SP.ip': [5.18562]}}}
Given a string that correspond to key level 3, what I want to do to have a construct
to check the existence in the dictionary based on choices below.
What's the way to do it. I tried this but failed.
choice1 = "LV.ip"
choice2 = "KK.ip"
choices = [choice1,choice2]
celltypes = ["DendriticCells", "Macrophages", "NKCells"]
for ch in choices:
for ct in celltypes:
if mydict["Foo"][ct][choices]:
print "THERE\n"
else:
print "Not there\n"
Your if statement should use ch, not choices
You should break up the test in that if; for example, make sure that mydict["Foo"][ct] exists before trying to see if it contains anything.
Consider using dict.get.
You might want to do something like mydict.get("Foo", {}).get(ct, {}).get(ch):. Essentially get a default empty dict that will default onto nothing towards the end.
Alternatively, use in to verify the keys. You might have something like
if ct in mydict['foo'] and ch in mydict['foo'][ct]:
Which should not fail due to lazy evaluation in Python.
You can use any function and in operator to check if the key exists in the dictionary or not.
for choice in choices:
for key in my_dict:
if any(choice in my_dict[key][key1] for key1 in my_dict[key]):
print "{} is there".format(choice)
Output
LV.ip is there
You are using the wrong variable name
choice1 = "LV.ip"
choice2 = "KK.ip"
choices = [choice1,choice2]
celltypes = ["DendriticCells", "Macrophages", "NKCells"]
for ch in choices:
for ct in celltypes:
if mydict["Foo"][ct][ch]: // change choices to ch
print "THERE\n"
else:
print "Not there\n"
this is not a programming question but a question about the IDLE. Is it possible to change the comment block key from '#' to something else?
here is the part that is not going to work:
array = []
y = array.append(str(words2)) <-- another part of the program
Hash = y.count(#) <-- part that won't work
print("There are", Hash, "#'s")
No, that isn't specific to IDLE that is part of the language.
EDIT: I'm pretty sure you want to use
y.count('#') # note the quotes
Remember one of the strengths of Python is portability. Writing a program that would only work with your custom version of the interpreter would be removing the strengths of the language.
As a rule of thumb anytime you find yourself thinking that solution is to rewrite part of the language you might be heading in the wrong direction.
You need to call count on the string not the list:
array = []
y = array.append(str(words2)) <-- another part of the program
Hash = y[0].count('#') # note the quotes and calling count on an element of the list not the whole list
print("There are", Hash, "#'s")
with output:
>>> l = []
>>> l.append('#$%^&###%$^^')
>>> l
['#$%^&###%$^^']
>>> l.count('#')
0
>>> l[0].count('#')
4
count is looking for an exact match and '#$%^&###%$^^' != '#'. You can use it on a list like so:
>>> l =[]
>>> l.append('#')
>>> l.append('?')
>>> l.append('#')
>>> l.append('<')
>>> l.count('#')
2
I need to test if the user input is the same as an element of a list, right now I'm doing this:
cars = ("red", "yellow", "blue")
guess = str(input())
if guess == cars[1] or guess == cars[2]:
print("success!")
But I'm working with bigger lists and my if statement is growing a lot with all those checks, is there a way to reference multiple indexes something like:
if guess == cars[1] or cars[2]
or
if guess == cars[1,2,3]
Reading the lists docs I saw that it's impossible to reference more than one index like, I tried above and of course that sends a syntax error.
The simplest way is:
if guess in cars:
...
but if your list was huge, that would be slow. You should then store your list of cars in a set:
cars_set = set(cars)
....
if guess in cars_set:
...
Checking whether something is present is a set is much quicker than checking whether it's in a list (but this only becomes an issue when you have many many items, and you're doing the check several times.)
(Edit: I'm assuming that the omission of cars[0] from the code in the question is an accident. If it isn't, then use cars[1:] instead of cars.)
Use guess in cars to test if guess is equal to an element in cars:
cars = ("red","yellow","blue")
guess = str(input())
if guess in cars:
print ("success!")
Use in:
if guess in cars:
print( 'success!' )
See also the possible operations on sequence type as documented in the official documentation.
#Sean Hobbs:
First you'd have to assign a value to the variable index.
index = 0
You might want to use while True to create the infinite loop, so your code would be like this:
while True:
champ = input("Guess a champion: ")
champ = str(champ)
found_champ = False
for i in listC:
if champ == i:
found_champ = True
if found_champ:
print("Correct")
else:
print("Incorrect")