H.G.
H.G.

Reputation: 35

Making list of unique numbers

I am trying to make a list of unique numbers and I am getting the wrong output.

I want to get each unique number from a file where each line has two numbers: friends=['4 6', '4 7', '4 8', '5 9', '6 8', '7 8', '100 112', '112 114', '78 44']

Answer: user=['4', '6', '7', '8','44','78', '100', '112', '114']

However my following code outputs user= ['0', '1', '2', '4', '5', '6', '7', '8', '9'] instead

I am unsure of how to make my code recognize two and three digit numbers in the file, basically this my problem

user=[]
for row in friends:
    for column in row:
            if column not in user and column.isdigit():
                user.append(column)

    user.sort()
print(user)

*I am not allowed to use dictionaries, sets, deque, bisect module

Upvotes: 0

Views: 80

Answers (2)

H.G.
H.G.

Reputation: 35

@downshift, I think I got it!! Thank you :)

def get_numbers(mylist):
    nums = [] 
    for i in mylist:                     
        nums.append(i.split())
        for i in range(len(nums)):
            for j in range(len(nums[0])):
                nums[i][j]= int(nums[i][j])
    return nums 

print(get_numbers(mylist))

Upvotes: 1

Something like this:

friends=['4 6', '4 7', '4 8', '5 9', '6 8', '7 8', '100 112', '112 114', '78 44']

def get_numbers(mylist):
    nums = []                            # create a new list
    for i in mylist:                     # for each pair in the friends list
        nums.append(map(int, i.split())) # split each pair
                                         # convert them to integers
                                         # and append them to the new list
    return nums                          # return the new list

numbers = get_numbers(friends)           # call the function with the old list

then you can do:

print(numbers)   
[[4, 6], [4, 7], [4, 8], [5, 9], [6, 8], [7, 8], [100, 112], [112, 114], [78, 44]]

This should help get you started. If you get stuck, post a comment, and we can update it.

Upvotes: 1

Related Questions