function for getting a value in a list - list

I need to create a function that accepts 1 argument (goblet) and return an empty list or a representation of [x, y] of a goblet.
def formate_a_goblet(goblet):
GOBLET_REPRESENTATION = {
1: ["▫", "◇", "◯", "□"],
2: ["▪", "◆", "●", "■"], }
if goblet == []:
return ""
else:
....
print(formater_un_gobblet([1, 2]))
>>> "◇"

Given a list of 2 numbers [x, y], we need to return the symbol present in the dictionary GOBLET_REPRESENTATION with key as x, and value at index y-1.
I tried it like this:
def fun(goblet):
GOBLET_REPRESENTATION = {
1: ["▫", "◇", "◯", "□"],
2: ["▪", "◆", "●", "■"], }
if goblet == []:
return ""
else:
return GOBLET_REPRESENTATION[goblet[0]][goblet[1]-1]

Related

How can I create a list with : separator?

I created a list of integer numbered with this function:
def collect_ints():
"""It returns the list of numbers entered by the user"""
ints = list()
keep_asking = True
while keep_asking:
n = input()
if n == "*":
keep_asking = False
if keep_asking:
ints.append(int(n))
return ints
However, in this way, I get a list of integers (on which I have to do some operations) with a comma (,) separator. How can I get the same list but with a : separator?
If you want to return exactly as a list data type it is not possible in python. But you can make it seem like a list using string formatting
def collect_ints():
ints = list()
keep_asking = True
while keep_asking:
n = input()
if n == "*":
keep_asking = False
if keep_asking:
ints.append(int(n))
output = "["
for i in ints:
output += "{}{}".format(i, ":")
output = output[:-1] + "]"
return output
The commas are used for visualizing lists. Lists do not have them, the print statement just prints them. So it is not possible to change them to other characters by default. But if you want to print them as a string with ':' as a delimiter, using 'replace' would be the best in my opinion.
def collect_ints():
"""It returns the list of numbers entered by the user"""
ints = list()
keep_asking = True
while keep_asking:
n = input()
if n == "*":
keep_asking = False
if keep_asking:
ints.append(int(n))
return str(ints).replace(',', ':')

Trying to create a new list of Odd numbers from a user inputted list?

This is my code. I have looked at many similar codes and have mine set up exactly how I should. I do not receive an error!
The problem is the output I receive is [11]. When the user inputs [1,2,3,4,5,6,7,8,9,11]. Why is it only pulling one odd number??
totlist = []
max_int = 10
oddlist = []
while len(totlist) < max_int:
nums = int(input('Enter a number: '))
totlist.append(nums)
def find_odds(totlist, oddlist):
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)
find_odds(totlist,oddlist)
print(oddlist)
You have forgoot the loop boucle inside the function
def find_odds(totlist, oddlist):
for item in range(len(totlist)) : # here
if len(totlist) == 0:
return
v = totlist.pop()
if v % 2 == 1:
oddlist.append(v)

python2.7: TypeError: unhashable type: 'list'

I have tried to find an answer to this in vain, so here goes:
The goal is to have a dictionary that has a few lists as values, and then have a function that (depending on user input) will take one of those lists and combine it with other lists, and finally I should get the final list printed.
Seems simple enough but what I get is a type error (lists being unhashable). The combine2 function seems to be working perfectly fine with any other two lists I try to feed it, except for when it tries to get a list that is a dictionary value (??). Does anybody know what I'm doing wrong?
dic = {
'reptiles': ['lizzard', 'crocodile', 'T-Rex'],
'birds': ['canary', 'parrot', 'seagul'],
'mammals': ['monkey', 'cat', 'dog'],
'insects': ['ant', 'bee', 'wasp']
}
FishList = ['goldfish', 'shark', 'trout']
def combine2 (a, b): # returns the combinations of 2 lists' items
tmp = []
n = 0
while n < len(a):
for i in b:
if 8 <= len(str(a[n])+str(i)) and 16 >= len(str(a[n])+str(i)):
tmp.append(str(a[n]) + str(i))
n += 1
return tmp
def animals_mix(k, l): # just some arbitrary combinations of lists
list1 = combine2(FishList, dic[k])
list2 = combine2(list1, dic[k])
list3 = combine2(dic[k], FishList)
l = dic[k] + list1 + list2 + list3
def animals():
print '''\n\nwhat's your favourite animal group?\n
1) reptiles
2) birds
3) mammals
4) insects
'''
while True:
x = raw_input("[+] pick a number > ")
tmp = []
if x == '1':
animals_mix(dic['reptiles'], tmp)
break
elif x == '2':
animals_mix(dic['birds'], tmp)
break
elif x == '3':
animals_mix(dic['mammals'], tmp)
break
elif x == '4':
animals_mix(dic['insects'], tmp)
break
elif x == '':
break
else:
print "\nError: That wasn't in the list of options\nType one of the numbers or press ENTER to move on\n"
return tmp
print animals()
For "TypeError: unhashable type: 'list'", it is because you are actually passing the list in your dict when you seemingly intend to pass the key then access that list:
animals_mix(dic['reptiles'], tmp)
...
def animals_mix(k, l):
list1 = combine2(FishList, dic[k])
in the first line of animals_mix() you are actually trying to do dic[dic['reptiles']] and dicts can not be keyed by un-hashable types, hence the error.

A Python return value

I have written a bisect function that takes a word list "t" and a word "val". It recursively halves the list until the index of the list is the word or returns false. If it finds the word, it is supposed to return it.
I have read multiple books, the documentation, and all the applicable questions here on SO but I still cannot determine what I am doing wrong: why won't the function return the value? It will print the value just fine, but no return except None.
Any help is greatly appreciated!
def bisect(t, val):
if t[len(t)/2] < val and len(t) > 1:
t = t[len(t)/2:]
bisect(t, val)
elif t[len(t)/2] > val and len(t) > 1:
t = t[:len(t)/2]
bisect(t, val)
elif t[len(t)/2] == val:
t = t[len(t)/2]
#print type(t), t
return t
else:
return False
b = make_list(t)
x = bisect(b, 'and')
print x
The main issue here is that you need to return t from each call to the recursively called function. Picture the call stack using my modified code below:
def main():
b = ['a', 'able', 'ability', 'abort', 'and', 'arc', 'zygote']
x = bisect(b, 'and')
print x
def bisect(t, val):
if t[len(t)/2] < val and len(t) > 1:
t = t[len(t)/2:]
t = bisect(t, val)
elif t[len(t)/2] > val and len(t) > 1:
t = t[:len(t)/2]
t = bisect(t, val)
elif t[len(t)/2] == val:
t = t[len(t)/2]
print type(t), t
else:
return False
return t
if __name__ == '__main__':
main()
The first time bisect is called, t is set to ['abort', 'and', 'arc', 'zygote'].
On the second call to bisect, t is set to ['abort', 'and']
On the third call, we have 'and' located, and return that value.
IF you returned as you had (only returning from the exact match or False result), then you return to the second call (['abort', 'and']), then the first call (['abort', 'and', 'arc', 'zygote']), and finally you return without hitting a return t in that first call. Thus, nothing is returned.
Rewriting your original code as I have, everything is the same until we find the match. However, with my code, the final call returns t back into the t variable used in the second call. That returns the value to the first call, which returns the result back to the calling code.
Hopefully, that clears up your question.
This modified version works:
def bisect(t, val):
mid = len(t)//2
mid_ele = t[mid]
end = len(t)
if mid_ele < val and end > 1:
t = t[mid:]
return bisect(t, val)
elif mid_ele > val and end > 1:
t = t[:mid]
return bisect(t, val)
elif mid_ele == val:
t = mid_ele
return t
else:
return False
b = ['she', 'he', 'you', 'and', 'me']
print(bisect(b, 'and'))
prints the desired:
and
I made it Python 3 proof using // for integer division and added two returnsbefore the recursive call.

find all ocurrences inside a list

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