Printing out a list object created by a class [duplicate] - python

This question already has answers here:
Why is `print(object)` displaying `<__main__. object at 0x02C08790>`?
(5 answers)
Closed 4 years ago.
I am trying to create a program, which generates a list of all the numbers in the range of 0 to any number, in random order and with each number appearing only once (in order to program some sorting algorithms and test them on this list afterwards). I tried to create a List() class, which takes as argument the length of the list it is supposed to create:
from random import randint, shuffle
class List():
def __init__(self, length):
self.length = length
def create_list(self):
list_ = [i for i in range(self.length)]
testlist = List(10)
print(testlist)
Now the problem is, instead of a list, the output of this code is just
<__main__.List object at 0x02DD1FF0>
Is there anybody who can tell me why and how to correct this?
Note that I'm a beginner, I began learning python about 2 weeks ago and this is more or less my first attempt in OOP...

You should override the __str__() method of the object. This is what gets called when you print an object that isn't inherently "printable"

Related

Python: how to append user input elements to an empty list [duplicate]

This question already has answers here:
Why does "x = x.append(...)" not work in a for loop?
(8 answers)
Closed 2 years ago.
I'm trying to create a list of size n whose elements are names - both are user inputs. Here is the following code:
names = []
for _ in range(int(input("Number of names to query (n): "))):
names = names.append(input("Enter the names to query: "))
I get an AttributeError: 'NoneType' object has no attribute 'append'
I don't understand what this means and why this is happening. names seems to be a list object?
print(type(names))
<class 'list'>
.append will edit the existing list. You don't need to assign it to a variable.
These types of methods in python often return None. So you are setting names to None and then trying to call .append on it again.

I need to make a program that takes the median of a list of numbers then finds the middle number [duplicate]

This question already has answers here:
Finding median of list in Python
(28 answers)
Closed 3 years ago.
I have a problem that one of the things i need to include is a subscript of median, but i have no clue what that means
I have tried most things but again i have no clue what subscript of median means.
def median(a):
a=a.sort()
a=len(a)/2
return a
def main():
print(median([3,1,2]))
print(median([4,3,2,1]))
print(median([1,5,3,2,4]))
print(median([6,5,1,2,3,4]))
main()
I expect it to print out the median of the numbers if it gets two i need the lesser... We cant use average.
You're returning the middle index, not the value of the element at that index.
Also, a.sort() modifies the list in place, it doesn't return the sorted list; a = a.sort() sorts the list and then sets a to None.
def median(a):
s = sorted(a)
middle = int(len(s)/2)
return s[middle]

How can I check if an object from one list is in another nested list? [duplicate]

This question already has answers here:
Python -Intersection of multiple lists?
(6 answers)
Closed 5 years ago.
say that I have a nested list like this for example:
List = [['a','d','b'],['a','x','w','t','d'],['g','c','d','z']]
and what I want to do is find the object in the List that all the smaller lists share, so for the example List I gave 'd' would be the object they all share.
here is what I have done so far:
def related(List):
for item in List[0]:
for i in range(1, len(List)):
if item in List[i]:
return item
the problem I am having is that when I do:
related([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
'a' is returned, but that isn't the correct answer since 'a' isn't in all the lists and only in the first 2 lists. The correct answer with that list should be 'd'.
My function basically just stops running once it finds the same object in just 1 of the lists.
Will someone be able to send me towards the right path on what I can do to get my code working correctly? Thank You!!!
What you're looking for here is the intersection of these lists. Python lists don't have an intersection functionality built-in, but sets do. We can do
def in_common(l):
if not l:
return set()
return set(l[0]).intersection(*l[1:])
This converts the first element to a set, and then finds the intersection of that set with the rest of the elements in the list.
in_common([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
returns
{'d'}
the set containing 'd'

Recursion with one argument [duplicate]

This question already has answers here:
calculate length of list recursively [duplicate]
(2 answers)
Closed 7 years ago.
So, my goal is to count the number of arguments in a list using recursion. However, as I'm only to use one argument in the function call, I don't know how to solve it without a second "count" argument.
So far I have this, where I accumulate the 1's together.
def countElements(a):
if a==[]:
return []
else:
return [1] + countElements(a[1:])
def main():
a=[3,2,5,3]
print(countElements(a))
main()
Instead of returning an empty list in the base case, return 0, and instead of [1] + countElements(a[1:]), return 1 + countElements(a[1:]). That way, you're just keeping the running count instead of getting a list back.

Mutable default arguments in Python [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I have written the following python program:
#!/usr/bin/env python
def bug( numbers = [] ):
numbers.append( 1 )
return numbers
print bug()
print bug()
The result i would expect is
[1]
[1]
But i got
[1]
[1, 1]
Is this a bug?
No, this is not a bug and this behaviour has been around in Python for a very long time.
The problem is that the list object is mutable, i.e. you can change it, and when you call a function you don't get a new default value. What's happening is this:
def bug( numbers = [] ):
numbers.append( 1 )
return numbers
At this point the function bug has been created and the list that is default value for numbers created.
print bug()
Now we've called bug once and added 1 to the list that was created when the function was defined.
print bug()
When we call the function again we get the same list as before so we get two 1s added to the list.
The usual solution is to define your function as follows:
def bug(numbers = None):
if numbers is None:
numbers = []
numbers.append(1)
return numbers
Read this for more details.
numbers=[] is evaluated only once (when the function is defined). So it's always the same list.
To avoid this, change the function like this:
def not_a_bug(numbers=None):
if numbers is None:
numbers = []
numbers.append(1)
return numbers

Categories