How can I create a list with : separator? - list

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(',', ':')

Related

Display all the longest words in a list in Python

I want to display all the words which are the longest in the list. I have used the max function, however the max function only returns the first of the largest string in the list i.e "have". How do I make it print out all the longest elements of the string?
Desirable output : 'have' 'been' 'good'
output obtained : 'have'
def longestWord(input_str):
input_list = input_str.split()
return max(input_list, key=len)
longestWord("I have been good")
output: 'have'
try this code thath compare the len of all items with the max len then append it to another list
def longestWord(input_str):
input_list = input_str.split()
lenght = len(max(input_list, key=len))
allMax=[]
for f in input_list:
if len(f) == lenght:
allMax.append(f)
print(f)
return allMax
longestWord("I have been good")

Replace items in list if condition

I need to replace temperature values in list depends on negative/positive and get rid of float at the same time. I.e. value '-0.81' should be '-1' (round) or '0.88' should be '1'.
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in range (len(myList)):
if myList[i][0] == '-' and int(myList[i][-2]) > 5:
do sth...
At the end I need new list with new values. Thank you for any tips.
Your code is already almost there. It's not necessary to reference the elements by index.
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
for i in myList:
if i[0] == '-' and int(i[-2]) > 5:
do sth...
If all you want to do is rounding then you can use a list comprehension.
roundlist = [round(float(i)) for i in myList]
You could parse the string into number, check for rounding (whether the decimal is higher or lower than 0.5), and convert it back to string
import math
myList = ['-1.02', '-1.03', '-0.81', '-0.17', '-0.07', '0.22', '0.88', '0.88', '0.69']
result = [0] * len(myList)
for i in range (len(myList)):
num = float(myList[i])
if num - math.floor(num) < 0.5:
result[i] = str(math.floor(num)) # round down
else:
result[i] = str(math.ceil(num)) # round up
print(result)

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.

writing a function to replicate data

im writing a function that takes in two parameters data which is meant to be replicated and times which is the number of times data should be replicated.
im new to python,can anyone help out
def replicate_iter(times, data):
output = times * data
if type(data) != str:
raise ValueError('Invalid')
if times <= 0:
return []
else:
return output.split(' ')
print replicate_iter(4, '5') #expected output [5, 5, 5, 5]
['5555']
This code is commented and will give you the desired output, but utilizes a for loop of size times.
def replicate_iter(times, data):
output = [] #you can initialize your list here
if type(data) != str:
raise ValueError('Invalid')
#if times <= 0: # Since input was initialized earlier
# return [] # These two lines become unnecessary
else:
for i in range(times): #use a for loop to append to your list
output.append(int(data)) #coerce data from string to int
return output #return the list and control to environment
print replicate_iter(4, '5')
Output is:
[5, 5, 5, 5]
You are returning output.split(' '), but your input '5' contains no spaces.
Therefore '5555'.split(' ') returns ['5555']. You will either need to change your return condition or add spaces between elements.
Adding spaces: (this assumes your string contains itself no spaces)
output = (times * (data + " ")).rstrip() # add a trailing space between elements and remove the last one
Changing the return / function: (this will support strings with spaces)
def replicate_iter(times, data):
output = []
if type(data) != str:
raise ValueError('Invalid')
while len(output) < times:
output.append(data)
return output

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