Checking if element is in tuple using if condition [duplicate] - python

This question already has answers here:
How to check if a tuple contains an element in Python?
(4 answers)
Closed 6 years ago.
I am trying to check if there is a certain digit inside my tuple using an if statement, but finding it hard. Whats wrong here?
def racaman(x):
y = x
w = (0,)
for i in range(y):
k = w[i]-x[i]
if k == i in w:
w = w + ((w[i]+x[i]),)
else:
w = w + ((w[i]-x[i]),)

You can replace 3 in the if condition to find a specific digit
def raceman(x):
#assuming x is tuple
if 3 in x:
print("found")
else:
print("not found")
raceman((1,2,3,4))

Please correct your question, paste code properly.
I am not sure what you are asking for but, I guess:
tupl = (1,2,3,4,5)
if 1 in tupl:
print('y')
else:
print('n')

I would recommend a list instead
def racaman(x):
w = [0]
for i in range(x):
k = w[i]-x[i]
if k in w: # fix this
w.append(w[i]+x[i])
else:
w.append(k) # already calculated
return w # did you want to return that?

This could simply be a matter of checking like so:
>>>n in t
Where n is the digit and t is the tuple, for example:
>>>2 in (1,2,3)
True
However it is not enough if you are looking for a digit and the elements are strings:
>>>2 in ('a1','a2','a3') #won't return desired output since digit '2' is part of a string
False
If so, you would need to resort to a more adaptive method, iterating over the elements of the tuple and testing each one with an appropriate regular expression (import re).

Related

Using Python, Is there a more elegant way to find the second largest number in a list? [duplicate]

This question already has answers here:
Get the second largest number in a list in linear time
(31 answers)
Closed 2 years ago.
I had this question come up in a job interview, and I was wondering if there were different ways to solve this. Preferably using Python 3.
Given a list of [20,40,20,60,80] find the second highest number.
The idea is to remove the duplicates. In one solution I've iterated over the list, and added any unique values to a list of uniques. Another way I did it was to convert the list to a set and back to a list, and then grab the second number.
So here's the question. Is there a better way to do this using Python 3?
Here's my code for solving in two different ways.
def second_item_method_1():
my_list = [20,40,20,60,80]
my_set = set(my_list)
my_list = list(my_set)
my_list.sort()
print(my_list[1])
def second_item_method_2():
my_list = [20,40,20,60,80]
unique_list = []
for x in my_list:
if x not in unique_list:
unique_list.append(x)
print(my_list[1])
second_item_method_1()
second_item_method_2()
Any other possible solutions?
You can iterate over the list twice in first iteration you can find the maximum element and in second iteration find the maximum element which is smaller than the first element.
def third_item_method():
list1 = [20, 40, 20, 60, 80]
mx=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
n =len(list1)
for i in range(2,n):
if list1[i]>mx:
secondmax=mx
mx=list1[i]
elif list1[i]>secondmax and mx != list1[i]:
secondmax=list1[i]
else:
if secondmax == mx:
secondmax = list1[i]
print("Second highest number is : ",str(secondmax))
third_item_method()
source: https://www.geeksforgeeks.org/python-program-to-find-second-largest-number-in-a-list/
Simplest thing I could come up with constraining myself to a single pass through the numbers.
Finds the two highest values. Only returns duplicates if no other alternative value in the list.
>>> def two_highest(li):
... a, b = li[:2]
... for i in li[1:]:
... if i > a:
... a, b = i, a
... elif i > b and i != a or a == b:
... b = i
... return (a, b)

Test the length of elements in a list

def lengthgood(x):
for i in x:
if len(i)<13
return i
else:
pass
def makeproperlist(x):
return x.split(',')
attendancelist=makeproperlist(input("attendee list:"))
final_list=list(filter(lengthgood,attendancelist))
for i in finallist:
print (i)
I want to write a programme of which I create a list in which only elements shorter than 14 can be a part of.
This is my code, but it keeps returning all the elements I put in, even if some of them are longer than 14?
I tried to print the len(i) and it says that it is 1 for every element in the list?
How do I solve this?
You shouldn't put a return within a loop; it'll only return the first element that matches your condition.
You also shouldn't be looping within your filter function, because you're actually looping over characters of strings, which are all length 1.
Therefore, the first character is always returning a truthy value, giving you back the initial input after filtering
You only need to check the input length, and filter functions should ideally return appropriate boolean conditions rather than truthy values (in your case return i is returning a non-empty string)
def lengthgood(x):
return len(x)<13
If you don't need to use filter(), you can write a list comprehension
final_list=[a if len(a) < 13 for a in attendancelist]
may be like that
flst = []
def croper(lst):
for i in lst:
flst.append(i) if len(i) < 13 else 0
lst = input("attendee list:").split(',')
croper(lst)
print(flst)
or shorter
def croper(lst):
return [i for i in lst if len(i) < 13]
lst = input("attendee list:").split(',')
print(croper(lst))
You want to create a list but you not define it anywhere in program simply done it with simply one function makeproperlist(x).
Try this code bro this will help you.
attendancelist=[]
while (True):
ch=input("Enter c for continue and e for exit : ")
if (ch=='c'):
def makeproperlist(x):
if x<=13:
attendancelist.append(x)
else:
print("Enter number which is <= to 13.")
makeproperlist(int(input("attendee list:")))
elif (ch=='e'):
break;
print("Your attendece list : ",attendancelist)

How to compare words in two lists according to same order in python?(I have def a function)

Recently, I def a function which can compare two words in each wordlist. However, I also found some problems here.
def printcorrectletters():
x=0
for letters in correctanswer:
for letters2 in userinput:
if letters == letters2:
x = x+1
break
return x
In this function, if the correctanswer='HUNTING', and I input 'GHUNTIN', it will show 6 letters are correct. However, I want it compare words' letters 1 by 1. So, it should march 0. For example, 'H' will match first letter of userinput.. and so on.
I also think another function which can solve it by using 'zip'. However, our TA ask me to finish it without things like 'zip'.
If the strings are different lengths, you want to compare each letter of the shorter string:
shortest_length = min(len(correctanswer), len(userinput))
min just gives you the minimum of two or more values. You could code it yourself as:
def min(a, b):
return a if a < b else b
You can index a character in a string, using [index]:
>>> 'Guanfong'[3]
n
So you can loop over all the letter indices:
correct = 0
for index in range(shortest_length):
if correctanswer[index] == userinput[index]:
correct += 1
If you did use zip and sum:
correct = sum(1 for (correct_char, user_char) in zip(correctanswer, userinput)
if correct_char == user_char)
Python provides great facilities for simplifying ideas and for communicating with the computer and programmers (including yourself, tomorrow).
Without zip you can use enumerate() to loop over elements of correctanswer , and get index and element at the same time. Example -
def printcorrectletters():
x=0
for i, letter in enumerate(correctanswer):
if i < len(userinput) and letter == userinput[i]:
x = x+1
return x
Or if even enumerate() is not allowed, simply use range() loop till len(correctanswer) and get elements from each index.

How to get the index in the 'in' statement in Python [duplicate]

This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 9 years ago.
I wrote an if statement like:
if word in vocab:
print word
However, I also would like to know the matched word index in vocab.
Is there any way in Python can do this?
I just come up a solution that use vocab.index(word) to get the index, but this way go through the array twice (one in if statement, one call index()). I wonder there should be more efficiency method.
Thanks.
To avoid one loop, you can use a try-except clause (without using if ... in ...:)
try:
i = vocab.index(word)
except ValueError as e:
print e # Optional
i = -1
This is a case where I wish I could do assignment in an if statement, but I can't so this is the solution:
If vocab is a list:
try:
index = vocab.index(word)
except ValueError:
pass
else:
print index, word
if vocab is a str:
index = vocab.find(word)
if index >= 0:
print index, word
def getindex(iterable,target):
for idx,value in enumerate(iterable):
if value==target: return idx
return -1
Note that this WILL NOT work if you're trying to find a substring in a string (as I'm assuming, since you're doing if word in vocab. In that case you really should do:
try: idx = iterable.index(target)
except ValueError as e: # Not found
# Handle it
If you try to use the getindex function above, it will always return -1 for any value len(target) > 1 since it will break your iterable into its smallest iteration, which is by-letter for strings.
You should have a look at pythons enumerate
EDIT: Following with an example:
for i, j in enumerate(vocab):
if j == word:
print (i, j)

finding the index of the first letter of a sub string in the main string

I am trying to find the index of the first letter of a sub string within the main string. The function acts exactly like the find method of python. I have created a find_chr function that gives me the index of a character in a string and I am using the find_chr to get the index of the substring.
def find_str(s,x):
i=0
if x in s:
return find_chr(s,x[i])
else:
return -1
My problem is that when I am using the string "IS GOING GOING" and substring as "ING", I am getting the index of the first "I", when I am expecting the index of the "I" of "ING". I will appreciate any input about changing the function to get the right index of the first letter of the substring.
In find_str you call find_chr(s,x[i]). This is calling find_chr with only x[i] (the ith part of the substring).
This should fix your problem
def find_chr(s,char):
i=0
step = len(char)
for j in range(len(s)+1):
ch = s[j:j+step]
if ch==char:
return (i)
break
i+=1
return -1
def find_str(s,x):
i=0
if x in s:
return find_chr(s,x)
else:
return -1
You aren't looping through the characters, you only check for i == 0 (i.e. the first character in s). You need to apply a "window" to the string, checking len(s) characters in a row:
def find_str(s, x):
if x in s: # is x present?
for i in range(len(s)): # work through string indices
if s[i:i+len(x)] == x: # does x start at current index?
return i
return -1
This should solve your problem:
def find_str(s, x):
i = 0
while i < len(s):
if s[i:i + len(x)] == x:
return i
else:
i += 1
print find_str('IS GOING GOING', 'ING')
Look up the use of the index function in strings. You will then happily replace all of that code with about 1 line.
Supplying the answer because of the following comments. Seriously though, if one is going to learn python, it is a good exercise to be aware of the methods available for an object.
>>> 'is going going'.index('ing')
5
or more generally
>>> fullstring.index(substring)
This should be marked as the correct answer because it is the simplest and most obviously correct. The complexity of the algorithms offered is way too high for this problem.
If the substring is not in the fullstring, a ValueError exception will be raised. So if you need a function, then it should return the index from a try or -1 (or None) from the except blocks.

Categories