How to compare an input() with a variable(list) - python-3.x

(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])

Related

Recreate the code without list comprehension

I am learning about list comprehension therefore i would like to recreate the code without list comprehension.
The code is the following:
items=[x for x in input().split(",")]
items.sort()
print (items)
This is how i recreated it:
print ("Enter comma seperated words: ")
userinput = input ().split(",")
words = []
for i in range (len(userinput)):
words.append(userinput)
words.sort()
print (words)
I expect the output should be in alphabetical order but it does not.
Let's say our input is this...
userinput = 'foo,bar'
Using the list comprehension code...
items=[x for x in userinput.split(",")]
items.sort()
print (items)
Output becomes: `['bar', 'foo']`
However, if we use your recreated code..
userinput = userinput.split(',')
words = []
for i in range (len(userinput)):
words.append(userinput)
words.sort()
print (words)
Output becomes: `[['foo', 'bar']]
Why is this?
When the line userinput = userinput.split(',') is run, userinput now becomes ['foo', 'bar'].
Therefore, when words.append(userinput) is run, what it is actually doing is saying words.append(['foo', 'bar']), and thus you are appending a list into a list meaning that words = [['foo', 'bar']].
words.sort() will not sort nested lists within itself, therefore, your list isnt sorted.
Therefore the fix is to append each element of userinput into words instead of appending userinput as a list into words.
userinput = userinput.split(',')
words = []
for i in range (len(userinput)):
words.append(userinput[i])
words.sort()
print (words)
Output becomes: ['bar', 'foo']

Is there a way to test if two separate values, in two separate arrays, and check if they are equal or not?

Im trying to see if a value in one array is equal to that in another array, the values are integer values.
Ive tried turning them into string and integers from the array but get the error that they cannot be converted implicitly.
winningnumber = []
usernumber = []
print(winningnumber)
print(usernumber)
if(winningnumber == usernumber):
print("Exact number")
I would then get an output like so
[1]
['1']
In order to do this, what you want to do is access the first item of each array, and compare that value.
There are a lot of ways to do this, but here is a little driver program to show you one way.
# Defining a function to see if they match
def is_winning(arr1, arr2):
# Grabbing the first element in each array
# denoted by the [0], for the "0th" element
arr1_first_ele = arr1[0]
arr2_first_ele = arr2[0]
# If the first element in the first array matches the first element in the second
if arr1_first_ele == arr2_first_ele:
# Print out they match
print("They match")
# Otherwise
else:
# Print out that they dont
print("They don't match")
def main():
# Example arrays
test_array_one = [1,3,4]
test_array_two = [5,4,3]
# This should print out "They don't match"
is_winning(test_array_one, test_array_two)
# Example arrays
test_array_three = [6,7,8]
test_array_four = [6,5,4]
# This should print out "They match"
is_winning(test_array_three, test_array_four)
main()
This evaluates to:
They don't match
They match

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.

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