-4

I read a file in python, which contains in each line 2 integer numbers and 1 real. How can i find in python the number of unique number from the 2 first integer number from all the file (except real)?

eg file

1 2 3.3
11 22 33.3
111 222 333.3
11 22 33.3
114 224 334.4

In this example, the result should be 8.

UPDATE this is my code

with open('test.txt','r') as f:
    for line in f:
        for word in line.split():
           print(word)

How can I determine not to consider the real number and after i can do count distinct number from the first two integer in each line

  • 2
    Please show what you have tried and which problems did you encounter. This way you have more chances to get help and less chances to get downvotes – Francesco Montesano Nov 25 '18 at 09:42
  • You read in the file line by line, split the line at spaces using `split()` . You convert the resulting strings into numbers, feed them into a set and check how big the set gets. What exactly is your problem? – Patrick Artner Nov 25 '18 at 09:43
  • SO is about fixing _your_ Code - not implementing your ideas. Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic) again and if you have questions provide your code as [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Patrick Artner Nov 25 '18 at 09:43
  • This is a question about several things: file reading, filtering, counting. Please show your attempt and which of these things you have trouble with (just one). But I'm quite sure it will turn out to be a question that has been asked before. – trincot Nov 25 '18 at 09:43
  • Check: [How to read a file line by line into a list](https://stackoverflow.com/q/3277503/5459839), [How to split a string into a list](https://stackoverflow.com/q/743806/5459839), [How to filter lists](https://stackoverflow.com/q/1596390/5459839), [How do I count unique values inside a list](https://stackoverflow.com/q/12282232/5459839) – trincot Nov 25 '18 at 09:52
  • i have update my question with my code – Elias Konstantinou Nov 25 '18 at 10:00

2 Answers2

1

You can use the set function to generate a unique set. For example:

fileName = 'test.txt'
with open(fileName, 'r') as f:
    unique = set()
    for line in f.readlines():
        unique = unique | set(line.split()[:2])
print(unique)

Output:

{'114', '11', '22', '111', '2', '224', '222', '1'}
cvanelteren
  • 1,633
  • 9
  • 16
0

After reading your file, you can get the set of every flattened row slices [:2], then get the length:

from itertools import chain

with open('numbers.txt') as file:
    unique = len(set(chain.from_iterable(x.split()[:2] for x in file)))
    print(unique)

# 8
RoadRunner
  • 25,803
  • 6
  • 42
  • 75