python print 3 strings of a list - python

I'm trying get the first 3 elements of a list.
1 a = "101.10.10.10"
2
3 b = "102.12.12.12"
4
5
6 asplit = a.split(".")
7 print("a - ")
8 print(asplit)
9
10 bsplit = b.split(".")
11 print("b - ")
12 print(bsplit)
13
14 print()
15 print()
16
17 print("---")
18 print (a[0], a[3])
when i'm using this code it returns
1 and .
i want to print
101 10 10
or
102 12 12

We can combine list comprehension, split() function, join() function and slicing to do that. At first, we split the string from dots. Then we create a list comprehension which will eliminate empty string. Then we join it, as a final step we use the [0:3] slice.
b = "102.12.12.12"
print(' '.join([x for x in b.split('.') if x != ''][0:3]))

In [1]: a = "101.10.10.10"
In [2]: " ".join(a.split(".")[:3])
Out[2]: '101 10 10'
In [3]: b = "102.12.12.12"
In [4]: " ".join(b.split(".")[:3])
Out[4]: '102 12 12'

Related

Flattening a 2d list into 1d list in python

I have a list of 2D elements
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
and I want my output to be:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
I tried this loop:
for i in range(3):
for k in range(i,len(m),3):
print(*m[i][k:k+3],sep='\t')
but it prints
1 2 3
4 5
6 7 8
9 10
11 12 13
14 15
16 17 18
and gives me an error
I'm not sure if it is possible since it is going on the next element. Can anyone help me on this?
An approach like this would work:
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
curr = 0
for i in m:
for j in i:
curr += 1
if(curr % 3 == 0):
print(j)
else:
print(j, end = ' ')
Output:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
You can create a variable, curr, to act as a counter variable. Then, iterate through every element of m, and increment curr with each iteration. For every third element, given by curr % 3 == 0%, we print an element WITH a newline. For every not-third element, we print the element without a newline.
I hope this helped! Please let me know if you have any further questions or clarifications :)
import itertools
x = list(itertools.chain(*m))
print([x[i:i+3] for i in range(0,len(x),3)])
Of course, the above will print the whole thing as a list of lists, but you can go from there to printing each of the individual sublists.
I would try something like
count = 0
for arr in matrix:
for num in arr:
print(num, end=' ')
count += 1
if count == 3:
print()
count = 0
one-line version:
print("".join([str(e)+" " if e%3!=0 else str(e)+"\n" for row in m for e in row]))
P.S. m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]] as that of OP.
easy-to-read version:
m does not need to be identical to that of OP. Could be any 2d matrix.
flat = [e for row in m for e in row]
for i in range(len(flat)):
if i%3 != 2 : print(flat[i], end = " ")
else : print(flat[i], end = "\n")
if len(flat)%3 != 0: print("")
You can use this snippet
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
flag=0
for i in range(len(m)):
for j in range(len(m[i])):
if(flag==3):
print()
flag=0
print(m[i][j],end=" ")
flag+=1
It has multiple ways to do that but easiest way is one line approaching using list comprrehension.
flat = [element for sublist in m for element in sublist]
m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
flat = [element for sublist in m for element in sublist]
print("Original list", m)
print("Flattened list", flat)
itertools.chain combines all the sublists, and more_itertools.chunked breaks that up into equal-sized segments.
from itertools import chain
from more_itertools import chunked
m = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]
for triplet in chunked(chain(*m), 3):
print(*triplet)
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
(The asterisks are for unpacking; in this case print(*triplet) is effectively the same as print(triplet[0], triplet[1], triplet[2]), and print automatically inserts a space between multiple arguments by default.)
P.S. Nine times out of ten, if you're mucking about with indexes in a Python loop, you don't need to.

While loop is not producing multiplication table [duplicate]

This question already has answers here:
Python check for integer input
(3 answers)
Closed 2 years ago.
i = 0
d = input("Enter the no. you want ")
while i < 11 :
print(i * d)
i+= 1
It is supposed to give multiplication table of d but it gives the following result for eg. '3' instead
3
33
333
3333
33333
333333
3333333
33333333
333333333
3333333333
The input() returns a string not an int and if you multiply a string in Python with an integer num, then you will get a string repeated num times. For example,
s = "stack"
print(s * 3) # Returns "stackstackstack"
You need to use int() constructor to cast the input from str to int.
d = int(input("Enter the no. you want "))
Try this:
d = int(input("Enter the no. you want "))
for i in range(1,11):
print(i * d)
In the above code, I have replaced your while loop construct with for loop and range() to get sequence of numbers.
BONUS:
To print/display the table in a nice and better way, try the below code:
for i in range(1,11):
print("%d X %d = %d" % (d, i, i * d))
Outputs:
Enter the no. you want 2
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20

Trouble in swapping and assignment min and max elements

IMPORTANT UPD AT THE END!
The existing code works not for all cases.
def myfunc(x):
a = [int(i) for i in x.split()]
a[a.index(min(a))], a[a.index(max(a))] = a[a.index(max(a))], a[a.index(min(a))]
a = [str(i) for i in a]
return ' '.join(a)
myfunc()
It works for 3 4 5 2 1 and don't work for 1 5 4 3 2.
Why?
!!!UPD: I made some changes and it looks very strange.
I used two different lines separately (with commented one of them). The program gives different results in some cases. BUT THE MOST INTERESTING, when I used two of them, uncommented - the program don't return the income string?
# a[a.index(min(a))], a[a.index(max(a))] = a[a.index(max(a))], a[a.index(min(a))]
a[a.index(max(a))], a[a.index(min(a))] = a[a.index(min(a))], a[a.index(max(a))]
Cases which I use:
#print(myfunc("5 1 4 3 2"))
#print(myfunc("1 5 4 3 2"))
#print(myfunc("3 4 5 2 1"))
#print(myfunc("-30000 30000"))
#print(myfunc("2147483647 -2147483648"))
#print(myfunc("1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 17 16 15 14"))
#print(myfunc("1 2 3 4 5 6 7 8 9 10"))
#print(myfunc("1 9 8 7 6 5 4 3 2 10"))
UPD+=1 Guys I changed code to:
minind = a.index(min(a))
maxind = a.index(max(a))
a[minind], a[maxind] = a[maxind], a[minind]
Now it works for all case. But question about previous cases are still open
Please help. I spend about 2 hours in tries to find some explanation of this...
Please help
The reason it doesn't work is because the assignments are being executed sequentially. When you write:
a[a.index(min(a))], a[a.index(max(a))] = a[a.index(max(a))], a[a.index(min(a))]
it's essentially equivalent to:
tempmax, tempmin = a[a.index(max(a))], a[a.index(min(a))]
a[a.index(min(a))] = tempmax
a[a.index(max(a))] = tempmin
But notice that after doing the tempmax assignment, a.index(max(a)) can change. index() returns the earliest index, so if the minimum element was before the maximum element, this will now return the original minimum element's location (because it now contains the maximum element), and assigns tempmin back to it.
Your code assumes that the indexes to be assigned are computed before any of the assignments are done, but that's not how it actually works.
Your code doesn't work if the minimum is located before the maximum.
For example:
s = "1 5 4 3 2" # this doesn't work
myfunc(s)
>>> '1 5 4 3 2'
s = "5 1 4 3 2" # this works
myfunc(s)
>>> '1 5 4 3 2'
But, as you noticed, if you define indices before swapping, everything works fine.
def myfunc(x):
a = [int(i) for i in x.split()]
mn = a.index(min(a))
mx = a.index(max(a))
a[mn], a[mx] = a[mx], a[mn]
a = [str(i) for i in a]
return ' '.join(a)
s = "1 5 4 3 2"
myfunc(s)
>>> '5 1 4 3 2'
I'm waiting for some illuminati mind to have an answer for this.

Write a program to prompt for square height h and print the even numbers in a square shape?

I'm not sure how to do this. I know how to print a square shape by prompting for row and col, but don't quite understand how to only prompt for height and print an array of even numbers.
col = eval(input("Enter the number of columns: "))
row = eval(input("Enter the number of rows: "))
for j in range(row):
for i in range(col):
print("*", end=" ")
print()
this is how I would set up printing a square of asterisks, but how would I do this while only prompting for height and printing out even numbers? For example, if my height is "3", it should print out an array that looks like this:
0 2 4
6 8 10
12 14 16
Using next() on an iterator of the numbers:
h = 3
ns = iter(range(0,h**2*2,2))
for r in range(h):
for c in range(h):
print(next(ns), end='\t')
print()
which gives:
0 2 4
6 8 10
12 14 16
Using slicing and str.join:
h = 4
ns = list(range(0,h**2*2,2))
for r in range(0,len(ns),h):
print(" ".join(str(c) + "\t" for c in ns[r:r+h]))
which gives:
0 2 4 6
8 10 12 14
16 18 20 22
24 26 28 30
Here is an approach by making a nested list and printing it out using a formatting function. Can replace the list comprehension with a generator comprehension for large lists.
def print_even_matrix(h):
l = [[2*(i + j) for j in range(h)] for i in range(0, h**2, h)]
listtab = lambda x: '\t'.join(map(str, x))
print '\n'.join(map(listtab, l))
>>> print_even_matrix(3)
0 2 4
6 8 10
12 14 16
>>> print_even_matrix(4)
0 2 4 6
8 10 12 14
16 18 20 22
24 26 28 30

Subtraction of one string values from another string values

I got two strings, called string1 and string2. Both consists of 6 different numbers.
What i would like to do in Python is to substract the values in string1 from the values in string2. How do I do this? I Guess this involves a for loop, since I only want to substract the first value in string1 from the first value in string2. And substract the second value from string1 from the second value in string2 etc.
So if string 1 got the numbers
2 5 8 9 6 3
and string 2 got the numbers
2 3 5 9 3 2
I want to take "string1" minus "string2" to get
0 2 3 0 3 1
Any suggestions?
You can achieve this with split(), zip(), and join():
" ".join([str(int(a) - int(b)) for a, b in zip(s1.split(), s2.split())])
Building on #pault answer, you can have the following variation (removed the calls to split(), added a conditional):
"".join([str(int(a) - int(b)) if a != ' ' else ' ' for a, b in zip(s1, s2)])
which is simply fancier way of doing:
" ".join([str(int(a) - int(b)) for a, b in zip(s1.replace(' ', ''), s2.replace(' ', ''))])
The latter might be more readable.
You can use regular expressions:
import re
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
new_string = ' '.join(str(a-b) for a, b in zip(map(int, re.findall('\d+', s1)), map(int, re.findall('\d+', s2))))
Output:
'0 2 3 0 3 1'
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
l1 = [int(x) for x in s1.split()]
l2 = [int(x) for x in s2.split()]
r1 = [v1 - v2 for v1, v2 in zip(l1, l2)]
.split() splits your string into a list based on where whitespace occurs (although you could provide it an argument to tell it to split on something else).
[int(x) for x in s1.split()] is a list comprehension. It's a one-line loop that does stuff for each value in a list (the split string). We need to convert the values in the split string into ints.
zip(l1, l2) takes the values in two lists and pairs them up. You'd need the lists to have the same number of elements for this to work (we do). From here, we use another list comprehension to pull out pairs of values and then take the difference.
edit (ty danihp): if you need the results to be a string, you can join the values in the list with ' '.join([str(x) for x in r1]) (this uses a space to separate elements in the list).
Step for step:
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
s3 = [int(x) for x in s1.split()] # split and convert to int
s4 = [int(x) for x in s2.split()] # split and convert to int
s5 = [] # result
for idx in range(0,len(s3)): # length are equal so this is ok
s5.append(s3[idx]-s4[idx]) # put into result
rv = " ".join([str(x) for x in s5]) # join result to string
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
print(rv)
Output:
2 5 8 9 6 3
2 3 5 9 3 2
[2, 5, 8, 9, 6, 3]
[2, 3, 5, 9, 3, 2]
[0, 2, 3, 0, 3, 1]
0 2 3 0 3 1
Since python is typed, you cannot subtact the strings: you have to convert each string to a list of integers and then subtract each one of the elements.
You can do this with only one loop:
s1 = '2 5 8 9 6 3'
s2 = '2 3 5 9 3 2'
list_diff = [int(x2) - int(x1) for x1, x2 in zip(s1.split(), s2.split())]
# or if you want the result as a string:
list_diff = [str(int(x1) - int(x2)) for x1, x2 in zip(s1.split(), s2.split())]
result = " ".join(list_diff)

Categories

Resources