i need to write a function that returns true if a list is a polindrom and false if it is not :
is_palindrome([]): True
is_palindrome([āsā]): True
is_palindrome([1,4,'g','g',4,1]): True
is_palindrome(['a','c','v']): False
is_polindrom[1,"g","1]: false
this is my code :
import copy
def is_polindrom(lst):
if len(lst)<=1:
return True
copy_lst = copy.copy(lst)
reverse_copy = copy_lst.reverse()
for i,j in reverse_copy,copy_lst:
if reverse_copy[i].type()==copy_lst[j].type() and reverse_copy[i]==copy_lst[j]:
return True
else:
return False
is_polindrom([1,2])
when i use ["s"] instead of true is doesnt return anything
and for :
is_polindrom([1,2]):
for i,j in reverse_copy,copy_lst:
TypeError: cannot unpack non-iterable NoneType object
i am not allowed to use negative or part indexes such as :
my_list[start:]
my_list[:end]
my_list[::step]
my_list[-idx]
my_list[:,idx]
thank you :)
Your code has 5 mistakes:
When you iterate through reverse_copy and copy_lst, you are doing
reverse_copy[i], copy_lst[j]
when you should just be doing
i, j
because in this case you are just iterating through each item, not through the INDEX of each item.
reverse() has no return value, therefore you cannot set a list to be the reverse list. You have to first create the list, then call
example_lst.reverse()
to reverse it.
You can't call type() like a method - it is a function, not a method. So instead of
i.type()
you must do
type(i)
In order to iterate through 2 lists at once, you must use the zip() function or else it doesn't work.
for i, j in zip(lst1, lst2):
You can't immediately return True after comparing one pair, otherwise when iterating through a list you'll just return True after just comparing the first items. Instead, you can add the result to an answer_list then return
all(answer_list)
which returns True if answer_list's items are all True.
(The reason is_polindrom returned False for [1, 2] was because you weren't using the zip() function so you weren't actually iterating through the items.)
Below is the full corrected code (note that I used Python's built-in list function to create a copy of lst):
def is_polindrom(lst):
if len(lst)<=1:
return True
copy_lst = list(lst)
reverse_copy = list(lst)
reverse_copy.reverse()
answer_list = []
for i,j in zip(reverse_copy,copy_lst):
if type(i)==type(j) and i==j:
answer_list.append(True)
else:
answer_list.append(False)
return all(answer_list)
lst = [1, 2]
# Prints is_polindrom([1, 2]): False
print("is_polindrom([1, 2]): " + str(is_polindrom(lst)))
print(lst) # Prints [1, 2]
Related
I need to get user input to generate a list of 8 numbers, but when they input a number that is already in the list print and error . Without using the in function to determine if its in the list. Here's what I have so far.
def main():
myList = range(9)
a= True
for i in myList:
while a == True:
usrNum = int(input("Please enter a number: "))
if usrNum != myList[i]:
myList.append(usrNum)
print(i)
main()
Error for above code,
Scripts/untitled4.py", line 18, in main
myList.append(usrNum)
AttributeError: 'range' object has no attribute 'append'
The issue seems to be your way of generating myList. If you generate it with myList = [range(9)] you'll get:
[[0, 1, 2, 3, 4, 5, 6, 7, 8]]
Try using simply:
myList = range(9)
Also, you need to change myList.append[usrNum] with myList.append(usrNum) or you'll get a:
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
You could also use wim's suggestion instead of the != operator:
if myList.__contains__(usrNum):
myList.append(usrNum)
There are two ways you can go about this:
Loop through the list to check each element.
The in operator is effectively doing:
for each value in the list:
if the value is what you're looking for
return True
if you reach the end of the list:
return False
If you can add that check into your code, you'll have your problem solved.
Use an alternate way of tracking which elements have been added
Options include a dict, or bits of an int.
For example, create checks = {}. When you add an value to the list, set checks[usrNum] = True. Then checks.get(usrNum, False) will return a boolean indicating whether the number already exists. You can simplify that with a collections.DefaultDict, but I suspect that may be more advanced than you're ready for.
The first is probably the result your instructor is after, so I'll give you a simple version to work with and massage to fit your needs.
myList = []
while True:
usrNum = int(input())
found = False
for v in myList:
if usrNum == v:
found = True
if not found:
myList.append(usrNum)
else:
#number was already in the list, panic!
Most instructors will be more impressed, and hence award better grades, if you can figure out how to do something like method 2, however.
You could do something like this, modify as needed (not sure when/if you want to break when the user enters a number that is already in the list, etc.)
This prompts for user input until they enter an item that already exists in the list, then it prints a message to the user, and stops execution.
def main():
mylist = range(9)
while True:
usrNum = int(input("Please enter a number: "))
if existsinlist(mylist, usrNum):
print("{} is already in the list {}".format(usrNum, mylist))
break
else:
mylist.append(usrNum)
def existsinlist(lst, itm):
for i in lst:
if itm == i:
return True
return False
Perhaps the point of this homework assignment is to help you understand how an operator like in is more efficient to read (and write, and compile) than the explicit loop that I used in the existsinlist function.
Not sure if list-comperehension would be allowable in this case, but you also could've done something like this, without relying on the existsinlist helper function:
def main():
mylist = range(9)
while True:
usrNum = int(input("Please enter a number: "))
if [i for i in mylist if i == usrNum]:
print("{} is already in the list {}".format(usrNum, mylist))
break
else:
mylist.append(usrNum)
In this case, the result of the list-comprehension can be evaluated for truthiness:
An empty list like [] results if no matching value exists, and this will be considered False
A non-empty list will result if at least one matching value exists, and this will be considered True
Yet another option which short-circuits and may be preferable:
if any(usrNum == i for i in mylist)
I am new to Python. I won't hide this is homework. I cannot figure out a way to iterate through multiple lists.
I originally wrote the below coding for one list ('lst') and it worked perfectly! Then I went back to add the other three lists and I don't know why I can't get it to work.
Any suggestions would be much appreciated. And if there are any tips on cleaning and refactoring, I'd appreciate it!.
result='False'
def magic(lst):
count=0
#Create a list.
if count == 0:
lst=[(4,9,2),(3,5,7),(8,1,6)]
count==1
result='True'
elif count==1:
lst=[(2,7,6),(9,5,1),(4,3,8)]
count==2
result='True'
elif count==2:
lst=[(1,2,3),(4,5,6),(7,8,9)]
count==3
result='True'
else:
lst=[(4,9,2),(3,5,5),(8,1,6)]
result='True'
return result
#set condition for magic square and print results
if is_row(let) and is_col(let) and is_diag(lst):
print('True')
else:
print("False")
#is_row function accepts a list as argument returns true or false
def is_row(lst):
if sum(lst[0]) == sum(lst[1]) == sum(lst[2]):
result_R = True
else:
result_R = False
return result_R
#is_col does the same thing as is_row
def is_col(lst):
for i in lst:
#select from the tuples in lst to make columns list
col1=[i[0] for i in lst]
col2=[i[1] for i in lst]
col3=[i[2] for i in lst]
if sum(col1) == sum(col2) == sum(col3):
result_C = True
else:
result_C = False
return result_C
def is_diag(lst):
#unpack all tuples into single list for easier indexing.
unpack1=[num for element in lst for num in element]
#Diagonal one slice
D1=unpack1[0:9:4]
#reverse list...simpler way of preparing for Diagonal Two
lst.reverse()
#unpack the reversed list
unpack2=[num for element in lst for num in element]
#Diagonal 2 slice
D2=unpack2[0:9:4]
#Condition for sum comparison
if sum(D1)==sum(D2):
result_D = True
else:
result_D = False
return result_D
magic(a,b,c,d)
In python I want to make a function that returns true if something is inside a list. Here is my example code.
def isin(List, value):
try:
i = List.index(value)
except ValueError:
return False
return True
For example in if I do
myList = [0,1,'string', 4.8]
isin(myList, 1) # I want to return True
isin(myList, 'animal') # I want to return False
Yes.
if 1 in myList # true
if "animal" in myList # false
Python has the in operator built-in for that:
myList = [0,1,'string', 4.8]
if 1 in myList:
# Do something
pass
print('animal' in myList) # Prints 'False'.
I am trying to append or add the sum of iterables through a range to an empty list. I was able to do it using a for loop:
list=[]
list_2=[]
def clique(n):
for i in range(n):
list.append(i)
list_2=sum(list)
print clique(4)
but everytime I try to do it within a function I get this error:
TypeError: range() integer end argument expected, got list.
the outputs is:
None
When you do print some_function(), the output is the return value of the function. If the function has no return statement, the return value is None by default. This is why print clique(4) prints None.
If you want print clique(4) to show the contents of list, then return list.
def clique(n):
for i in range(n):
list.append(i)
list_2=sum(list)
return list
try this:
list=[]
def clique(n):
for i in range(n):
list.append(i)
list_2=sum(list)
print 'list', list
print 'list_2', list_2
clique(4)
I'm trying to implement a function to find occurrences in a list, here's my code:
def all_numbers():
num_list = []
c.execute("SELECT * FROM myTable")
for row in c:
num_list.append(row[1])
return num_list
def compare_results():
look_up_num = raw_input("Lucky number: ")
occurrences = [i for i, x in enumerate(all_numbers()) if x == look_up_num]
return occurrences
I keep getting an empty list instead of the ocurrences even when I enter a number that is on the mentioned list.
Your code does the following:
It fetches everything from the database. Each row is a sequence.
Then, it takes all these results and adds them to a list.
It returns this list.
Next, your code goes through each item list (remember, its a sequence, like a tuple) and fetches the item and its index (this is what enumerate does).
Next, you attempt to compare the sequence with a string, and if it matches, return it as part of a list.
At #5, the script fails because you are comparing a tuple to a string. Here is a simplified example of what you are doing:
>>> def all_numbers():
... return [(1,5), (2,6)]
...
>>> lucky_number = 5
>>> for i, x in enumerate(all_numbers()):
... print('{} {}'.format(i, x))
... if x == lucky_number:
... print 'Found it!'
...
0 (1, 5)
1 (2, 6)
As you can see, at each loop, your x is the tuple, and it will never equal 5; even though actually the row exists.
You can have the database do your dirty work for you, by returning only the number of rows that match your lucky number:
def get_number_count(lucky_number):
""" Returns the number of times the lucky_number
appears in the database """
c.execute('SELECT COUNT(*) FROM myTable WHERE number_column = %s', (lucky_number,))
result = c.fetchone()
return result[0]
def get_input_number():
""" Get the number to be searched in the database """
lookup_num = raw_input('Lucky number: ')
return get_number_count(lookup_num)
raw_input is returning a string. Try converting it to a number.
occurrences = [i for i, x in enumerate(all_numbers()) if x == int(look_up_num)]