python script to find the unique value - python

I have a script to find the unique value from 2 files
1.csv
11 12 13 14
21 22 23 24
11 32 33 34
2.csv
41 42 43 44 45
51 52 53 54 55
41 62 63 64 65
script is:
import csv
import sys
# Count all first-column numbers.
counts = {}
# Loop over all input files.
for a in sys.argv[1:]:
# Open the file for reading.
with open(a) as c:
# Read it as a CSV file.
reader = csv.reader(c, delimiter=' ')
for row in reader:
count = counts.get(row[0], 0)
# Increment the count by 1.
counts[row[0]] = count + 1
# Print only those numbers that have a count of 1.
print([i for i, c in counts.items() if c == 1])
Usage:
$ python 1.py 1.csv 2.csv
output is
['51', '21']
but i want the output in different row like
51
21

Use string.join to join the list items on a \n:
l = ['51', '21']
print("\n".join(l))
Edit:
In your code (which actually is from an answer I gave you yesterday), do this:
print("\n".join([i for i, c in counts.items() if c == 1]))

Replace the last line by the following:
for result, count in counts.items():
if count == 1:
print(result)
It's not the most concise way to do it but at least it's quite readable

Related

Removing last line and initial whitespaces from an 8 by 8 list of integers in python

#Print the user board
s = ''
for i in range(n):
for j in range(n):
z = i * n + j
s += ' '
if z < 10:
s += ' '
s += str(z)
s += '\n'
print(dedent(s))
queens = list(map(int, input("Queens: ").split()))
I keep getting an error from my testcase environment of a last blank line before proceeding to the queens input below. What can I approach to fix
I have tried cleandoc from textwrap and while it works, it disrupts every required spacing and new distinctive lines for z from the "s" string which is a perfect 8 by 8 from 0 to 63.
Creating the right way instead of removing things after is easier:
from itertools import count
import toolz
n = 8
start_value = 0
counter = count(start_value)
rows = [" ".join(f"{num:2}" for num in toolz.take(n, counter)) for _ in range(n)]
print("\n".join(rows))
The itertools.count creates an iterable counter that gives the next value every time you want. Here the take function will get 8 items each time.
If you do not want the initial space, you'd better use join, which only adds the separator between consecutive items:
s = '\n'.join(' '.join('{:2d}'.format(i * n + j)
for j in range(n))
for i in range(n))
print(s)
gives as expected:
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63

How to print minimal value from two dimensional array

Hello everyone here is my code:
n =[[34,2,55,24,22],[31,22,4,7,333]]
for r in n:
for c in r:
print(c,end = " ")
print()
sums=[]
for i in n:
sum=0
for num in i:
sum+=int(num)
sums.append(sum)
print(*sums)
mini = min([min(r) for r in n])
print(mini)
#This is what it prints out
34 2 55 24 22
31 22 4 7 333
137 397
2
As you can see it prints out smallest number from all array how i can print out smallest number from both rows i have tried using numpy but i have error and then i need to do something to files to fix it which i dont want to do can you please tell me another solution Last thing i need to print it out by changing rows like this and then all other stuff:
31 22 4 7 333
34 2 55 24 22
137 397
4 2
You only need to get the minimum of each row, not the minimum of that.
print(*(min(row) for row in n))
you can use numpy
>>> n = np.array([[34,2,55,24,22],[31,22,4,7,333]])
>>> n.min(axis=1)
array([2, 4])
>>>

Trying to print all my items in a list to rows and columns

So im trying to print the items from the list in to a 18x4 matrix or a table. I´ve tried doing it by using format but it hasn't seem to work.
This is the desired output I want to get from the list, but im not sure how to print the first 18 items in one column and then the next 18 items in second column and so forth. I hope the description is well enough explained since english is not my first language. Any help would be greatly appreciated.
Use nested loops for the rows and columns. In the inner loop, use a stride of 18 to get every 18th element starting from the index in the first column.
for i in range(18):
for j in range(i, len(wireless_node_list), 18):
print(wireless_node_list[j], end='\t')
print()
You'll need to layout each row of output. Figuring out how many rows to display requires some basic math if the goal is to have a target number of columns:
# Some sample data
values = [x / 7 for x in range(50)]
cols = 4
# Figure out how many rows are needed
rows, extra = divmod(len(values), cols)
if extra > 0:
# That means we need one final partial row
rows += 1
# And show each row in turn
for row in range(rows):
line = ""
for col in range(cols):
i = col * rows + row
if i < len(values):
line += f"{i:3d} {values[i]:3.9f} "
print(line)
Which outputs:
0 0.000000000 13 1.857142857 26 3.714285714 39 5.571428571
1 0.142857143 14 2.000000000 27 3.857142857 40 5.714285714
2 0.285714286 15 2.142857143 28 4.000000000 41 5.857142857
3 0.428571429 16 2.285714286 29 4.142857143 42 6.000000000
4 0.571428571 17 2.428571429 30 4.285714286 43 6.142857143
5 0.714285714 18 2.571428571 31 4.428571429 44 6.285714286
6 0.857142857 19 2.714285714 32 4.571428571 45 6.428571429
7 1.000000000 20 2.857142857 33 4.714285714 46 6.571428571
8 1.142857143 21 3.000000000 34 4.857142857 47 6.714285714
9 1.285714286 22 3.142857143 35 5.000000000 48 6.857142857
10 1.428571429 23 3.285714286 36 5.142857143 49 7.000000000
11 1.571428571 24 3.428571429 37 5.285714286
12 1.714285714 25 3.571428571 38 5.428571429
This is a bit brute force, but should work. Just build your list and then do a little math with your indexes.
list = ["112312", "12321312", "9809809", "8374973498", "3827498734", "5426547", "08091280398", "ndfahdda", "ppoiudapp", "dafdsf", "huhidhsaf", "nadsjhfdk", "hdajfhk", "jkhjhkh", "hdjhkajhkj"]
build = {}
len = len(list)
rowCount = len//4 + 1
for i in range(rowCount):
build[i] = []
if i < len: build[i].append(list[i])
if i + 4 < len: build[i].append(list[i + 4])
if i + 8 < len: build[i].append(list[i + 8])
if i + 12 < len: build[i].append(list[i + 12])
print(build)
This little sample tested out fine for me.

Why can't I find max number in a file like this?

I'm quite new to python, though I have a lot of experience with bash. I have a file that consists of a single column of numbers, and I would like to find the largest number in the list. I tried to do so with the following code:
i = 0
with open('jan14.nSets.txt','r') as data:
for num in data:
if num > i:
i = num
print(i)
where jan14.nSets.txt is the following:
12
80
46
51
0
64
37
9
270
23
132
133
16
6
18
23
32
75
2
9
6
74
44
41
56
17
9
4
8
5
3
27
1
3
42
23
58
118
100
185
85
63
220
38
163
27
198
Rather than 270, I receive 9 as an output, and I do not understand why this is the case. I know that there are builtins for this, but I would like to know why this doesn't work to help me understand the language. I am using python2.7
num is a string, not a number. Turn it into an integer first using int():
num = int(num)
You are comparing text, so it is ordered lexicographically, '9' > '80' because the ASCII character '9' has a higher codepoint than '8':
>>> '9' > '80'
True
After the '9' line, all other lines either have an initial digit that is smaller than '9', or the line is equal.
You could use the max() function instead, provided you first use map() to turn all lines into integers:
with open('jan14.nSets.txt','r') as data:
i = max(map(int, data))
or use a generator expression (in Python 2, more memory efficient than map()):
with open('jan14.nSets.txt','r') as data:
i = max(int(num) for num in data)
Both pull in all lines from data, map the lines to integers, and determine the maximum value from those.

Converting coordinate representation to adjecency list representation

What is the most efficient way to convert this file:
10 3
10 5
12 6
12 19
19 12
19 14
19 10
to this:
10 3 5
12 6 19
19 12 14 10
First column of the input file is numerically sorted in increasing order.
Any solutions using Python, AWK, etc. are welcome.
from itertools import groupby
lines, op_file = [line.split() for line in open("In.txt")], open("Out.txt", "w")
for key, grp in groupby(lines, key = lambda x: x[0]):
print >> op_file, "{} {}".format(key, " ".join([i[1] for i in grp]))
op_file.close()
Output
10 3 5
12 6 19
19 12 14 10
Since you mentioned awk:
$ awk '{a[$1]=a[$1]" "$2}END{for (i in a){print i a[i]}}' input
19 12 14 10
10 3 5
12 6 19
pipe it to sort to have it, well, sorted:
$ awk '...' input | sort
10 3 5
12 6 19
19 12 14 10
In Python 2:
import itertools, operator
with open(infilename) as infile:
input = (line.split() for line in infile)
output = itertools.groupby(input, operator.itemgetter(0))
with open(outfilename, 'w') as outfile:
for key, line in output:
print >>outfile, key, ' '.join(val[1] for val in line)
This assumes that the input and output files are different: you could just write the output to standard out and leave it as the user's problem to save it.
Try out this code
fp = open('/tmp/test.txt')
list_dict = {}
for line in fp.readlines():
split_values = line.split()
if split_values[0] in list_dict:
list_dict[split_values[0]].extend(split_values[1:])
else:
list_dict[split_values[0]] = split_values
for val in list_dict.values():
print " ".join(val)

Categories

Resources