Append/add sum to list - python-2.7

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)

Related

polindrom in python function for list

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]

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

For-Loop a list returning a None value in the end

Why is it when executing this code, the final return is a None?
def evenNum(x):
for num in x:
if num%2==0:
print num
a = [1,2,3,4,5,6,7,8,9,10]
print evenNum(a)
How do i omit that None value?
Because you do not return any value in your function. If you want to have the list of even numbers you should do some thing like this:
def evenNum(x):
even_nums = []
for num in x:
if num%2==0:
even_nums.append(num)
print num
return even_nums
Your function does not return anything, or, in other words, it returns None. Replace:
print evenNum(a)
with:
evenNum(a)
to avoid None being printed.
evenNum - Its function returns no value, then the default is to return None

How to add a element to the next list everytime a new value is entered?

For example I have a list with a month and the month number, I want to add in another value in [0][1], [1][1],[2][1] every time I input a new value. I'm thinking of the append function however I'm unsure how to re-code that to make that value to input into the the next list along in the list.
list = [[['Jan'],1], [['Feb'],2],[['Mar'],3]]
def month():
global list
count = 0
while value_count < 3:
value = int(input("Enter a value: "))
if value in range(101):
list[0][1].append(value)
count += 1
else:
print('Try Again.')
month()
I want to result with something like:
list = [[['Jan'],1,54], [['Feb'],2,65],[['Mar'],3,62]]
Where 54, 65 and 62 are random numbers a user has entered.
Please see the comments in the code
# list is a function used by python to create lists,
# do not use builtins' names for your variables
my_list = [[['Jan'],1], [['Feb'],2],[['Mar'],3]]
def month():
# print("Don't use globals!\n"*100)
# you can pass arguments to a function, like in "def mont(my_list)"
global my_list
# cycling on a numerical index is complicated, use this syntax
# instead, meaning "use, in turn, the same name to refer to each
# element of the list"
for element in my_list:
value = int(input("Enter a value: "))
# if value in range(101):
if 1: # always true, the test doesn't work as you expect
element.append(value)
else:
print('Try Again.')
month()
print my_list
you can write the input loop like this
value = 101
while not (0<=value<101):
value = int(input(...)
element.append(value)
this way you'll miss the alternative prompt but it's good enough.

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