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

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

Related

Palindrome problem - Trying to check 2 lists for equality python3.9

I'm writing a program to check if a given user input is a palindrome or not. if it is the program should print "Yes", if not "no". I realize that this program is entirely too complex since I actually only needed to check the whole word using the reversed() function, but I ended up making it quite complex by splitting the word into two lists and then checking the lists against each other.
Despite that, I'm not clear why the last conditional isn't returning the expected "Yes" when I pass it "racecar" as an input. When I print the lists in line 23 and 24, I get two lists that are identical, but then when I compare them in the conditional, I always get "No" meaning they are not equal to each other. can anyone explain why this is? I've tried to convert the lists to strings but no luck.
def odd_or_even(a): # function for determining if odd or even
if len(a) % 2 == 0:
return True
else:
return False
the_string = input("How about a word?\n")
x = int(len(the_string))
odd_or_even(the_string) # find out if the word has an odd or an even number of characters
if odd_or_even(the_string) == True: # if even
for i in range(x):
first_half = the_string[0:int((x/2))] #create a list with part 1
second_half = the_string[(x-(int((x/2)))):x] #create a list with part 2
else: #if odd
for i in range(x):
first_half = the_string[:(int((x-1)/2))] #create a list with part 1 without the middle index
second_half = the_string[int(int(x-1)/2)+1:] #create a list with part 2 without the middle index
print(list(reversed(second_half)))
print(list(first_half))
if first_half == reversed(second_half): ##### NOT WORKING BUT DONT KNOW WHY #####
print("Yes")
else:
print("No")
Despite your comments first_half and second_half are substrings of your input, not lists. When you print them out, you're converting them to lists, but in the comparison, you do not convert first_half or reversed(second_half). Thus you are comparing a string to an iterator (returned by reversed), which will always be false.
So a basic fix is to do the conversion for the if, just like you did when printing the lists out:
if list(first_half) == list(reversed(second_half)):
A better fix might be to compare as strings, by making one of the slices use a step of -1, so you don't need to use reversed. Try second_half = the_string[-1:x//2:-1] (or similar, you probably need to tweak either the even or odd case by one). Or you could use the "alien smiley" slice to reverse the string after you slice it out of the input: second_half = second_half[::-1].
There are a few other oddities in your code, like your for i in range(x) loop that overwrites all of its results except the last one. Just use x - 1 in the slicing code and you don't need that loop at all. You're also calling int a lot more often than you need to (if you used // instead of /, you could get rid of literally all of the int calls).

returning a list from multiple mixed args

I'm trying to write a function that accepts a list of numbers either as a single number or a range, the expected input syntax will be: 1,2 ,3-5, 7,9 -4
The function will be returning a list of string 'numbers'.
So this will be: '1','2','3','4','5','7','9','8','7','6','5','4'. Spaces should be removed.
which will have duplicates removed: '1','2','3','4','5','7','9','8','6'.
It would be nice to have these ordered ascending, but optional
Method
My first issue seems to be accepting 3-5 as a string, it is automatically returned as -2 so this needs to be identified and sent to list(map(str, range(3, 5))) [plus 1 to the highest number since it's python] this range can then be added to the listl.
Any single numbers can be appended to the list.
Duplicates are removed (solved).
The list is returned.
My outline
def get_list(*args):
# input 1-10,567,32, 45-78 # comes in as numbers, but should be treated as string
l=[] # new empty list
n=str(args) # get the args as a string
# if there is a '-' between 2 numbers get the range
# perhaps convert the list to a np.array() then loop through?
# I will need n.split(',') somewhere?
l = list(map(str, range(3, 5)))
# if just a single number append to list
l.append()
# remove duplicates from list
def remove_list_duplicates(l):
return list(dict.fromkeys(l))
l = remove_list_duplicates(l)
return l
Here's my solution for your problem:
ranges = input()
ranges = ranges.split(',') # i split the user input on ',' as i expect the user to specify the arguments with a ',' else you can split it on ' '(space)
def get_list(*ranges):
return_list = [] # initialize an empty list
for i in ranges:
try: # as these are strings and we need to process these exceptions may occur useexception handling
return_list.append(int(i)) # add the number to the list directly if it can be converted to an integer
except:
num_1,num_2 = map(int,i.split('-')) # otherwise get the two numbers for the range and extend the range to the list
if(num_1 > num_2):
return_list.extend([j for j in range(num_2,num_1 + 1 ,1)])
else:
return_list.extend([j for j in range(num_1,num_2 + 1 ,1)])
return list(set(return_list)) # to return a sorted and without duplicates list use the set method
print(get_list(*ranges)) # you need to use the spread operator as the split method on input returns a list
Ouptput:

Finding a substring in a jumbled string

I am writing a script - includes(word1, word2) - that takes two strings as arguments, and finds if word1 is included in word2. Word2 is a letter jumble. It should return Boolean. Also repetition of letters are allowed, I am only checking if the letters are included in the both words in the same order.
>>>includes('queen', 'qwertyuytresdftyuiokn')
True
'queen', 'QwertyUytrEsdftyuiokN'
I tried turning each word into lists so that it is easier to work with each element. My code is this:
def includes(w1, w2):
w1 = list(w1)
w2 = list(w2)
result = False
for i in w1:
if i in w2:
result = True
else:
result = False
return result
But the problem is that I need to also check if the letters of word1 comes in the same order in word2, and my code doesn't controls that. I couldn't find a way to implement that with list. Just like I couldn't do this much with strings, so I think I need to use another data structure like dictionary but I don't know much about them.
I hope I understood what is your goal.
Python is not my thing, but I think I made it pythonic:
def is_subsequence(pattern, items_to_use):
items_to_use = (x for x in items_to_use)
return all(any(x == y for y in items_to_use) for x, _ in itertools.groupby(pattern))
https://ideone.com/Saz984
Explanation:
itertools.groupby transfers pattern in such way that constitutive duplicates are discarded
all items form form grouped pattern must fulfill conditions
any uses generator items_to_use as long as it doesn't matches current item. Note that items_to_use mus be defined outside of final expression so progress on it is kept every time next item from pattern is verified.
If you are not just checking substrings:
def include(a, b):
a = "".join(set(a)) # removes duplicates
if len(a) == 1:
if a in b:
return True
else:
return False
else:
try:
pos = b.index(a[0])
return include(a[1:], b[pos:])
except:
return False
print(include('queen', 'qwertyuytresdftyuiokn'))
#True

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

Function that removes zeroes from list?

I just need a function that removes zeroes from an input list
def no_zero(a):
pos=0
while (pos+1)<=len(a):
if a[pos] == "0":
a.remove[pos]
pos= pos +1
return a
print(no_zero([0,1,0,2,0,3]))
I should be getting an output of 1,2,3 but instead it skips right to return a. Any pointers as to why? Cheers.
You can use a list comprehension:
def no_zero(a):
return [x for x in a if x != 0]
print(no_zero([0,1,0,2,0,3]))
Additionally, the reason your code currently isn't working is because you are comparing the items to a string ("0") instead of an integer (0). You are also attempting to modify a list as you iterate over it, which means that your indices don't correspond to the original indices of the list, and your result will be wrong.

Resources