For a tutorial, I need to output the following table on python using nested for loops:
asc: 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
chr: 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
asc: 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
chr: # A B C D E F G H I J K L M N O
asc: 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
chr: P Q R S T U V W X Y Z [ \ ] ^ _
asc: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
chr: ` a b c d e f g h i j k l m n o
asc: 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
chr: p q r s t u v w x y z { | } ~
asc: 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127'''
Since this is the beginners class we have not learned def. This question has been answered in previous posts but the answers use def and I cannot
So far my code looks like this:
X=0
for Rows in range(0,12,2):
X=X+1
if Rows%2==0:
print('chr:',end="")
for chrColumns in range (32,48):
print('%4s'%chr(chrColumns+(X-1)*16), end="")
print()
if Rows%2==1:
print('asc:',end="")
for ascColumns in range (16,32):
print(ascColumns+(X-1)*16,end="")
print()
I cannot find a way for the "chr:" rows to alternate with "asc:" rows. Please help me
How about something like this?
for c in range(32, 128, 16):
#print chr line
for c1 in range(c, c+16):
# print chr
#print asc line
for c2 in range(c, c+16):
# print asc
for c in range(32, 128, 16):
print('chr:',end="")
for c1 in range(c, c+16):
print('%4s'%chr(c1), end="")
print()
print('asc:',end="")
for c2 in range(c, c+16):
print('%4s'%c2, end="")
print()
Here's my inelegant solution:
P = 32
for line in range (0,6):
print ("chr:", end = " ")
for chrCols in range (P,P+16):
print (chr(chrCols), end=" ")
print ('\n' "asc: ", end = "")
for ascCols in range (P,P+15):
if ascCols < 100:
print (ascCols, end=" ")
if ascCols > 99:
print (ascCols, end=" ")
print(ascCols+1)
P = P + 16
servers = ["server1", "server2", "server3"]
table_column = 2
row_format ="{:>15}" * (table_column)
print(row_format.format("Server", "Status"))
print ("--"*18)
for server in servers:
print(row_format.format(server, "code"))
Output
Related
def display_code_ascii():
for i in range(32, 128):
print(chr(i))
print(display_code_ascii())
This is my code. the output is:
!
"
#
$
%
&
'
(
)
*
+
,
-
.
/
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?
#
A
B
C
D
E
But I want to print in a console like this:
32 is 33 is ! 34 is " 35 is # 36 is $ 37 is % 38 is & 39 is ' 40 is ( 41 is )
42 is * 43 is + 44 is , 45 is - 46 is . 47 is / 48 is 0 49 is 1 50 is 2 51 is 3
52 is 4 53 is 5 54 is 6 55 is 7 56 is 8 57 is 9 58 is : 59 is ; 60 is < 61 is =
62 is > 63 is ? 64 is # 65 is A 66 is B 67 is C 68 is D 69 is E 70 is F 71 is G
72 is H 73 is I 74 is J 75 is K 76 is L 77 is M 78 is N 79 is O 80 is P 81 is Q
82 is R 83 is S 84 is T 85 is U 86 is V 87 is W 88 is X 89 is Y 90 is Z 91 is [
92 is \ 93 is ] 94 is ^ 95 is _ 96 is ` 97 is a 98 is b 99 is c 100 is d 101 is e
102 is f 103 is g 104 is h 105 is i 106 is j 107 is k 108 is l 109 is m 110 is n 111 is o
112 is p 113 is q 114 is r 115 is s 116 is t 117 is u 118 is v 119 is w 120 is x 121 is y
122 is z 123 is { 124 is | 125 is } 126 is ~ 127 is None
# set chunk_size which is number of initial elements to handle per each outputted line
chunk_size = 10
def format_element(x):
x = chr(x)
return x if x != '\x7f' else "None"
# prepare initial list elements with output strings
ll = [f"{x} is {format_element(x)}" for x in range(32, 128)]
# split list into chunks using chunk_size
ll = [ll[i:i+chunk_size] for i in range(len(ll))[::chunk_size]]
# join inner lists into output lines strings
ll = [" ".join(x) for x in ll]
# print each line separately
for i in ll:
print(i)
Output:
32 is 33 is ! 34 is " 35 is # 36 is $ 37 is % 38 is & 39 is ' 40 is ( 41 is )
42 is * 43 is + 44 is , 45 is - 46 is . 47 is / 48 is 0 49 is 1 50 is 2 51 is 3
52 is 4 53 is 5 54 is 6 55 is 7 56 is 8 57 is 9 58 is : 59 is ; 60 is < 61 is =
62 is > 63 is ? 64 is # 65 is A 66 is B 67 is C 68 is D 69 is E 70 is F 71 is G
72 is H 73 is I 74 is J 75 is K 76 is L 77 is M 78 is N 79 is O 80 is P 81 is Q
82 is R 83 is S 84 is T 85 is U 86 is V 87 is W 88 is X 89 is Y 90 is Z 91 is [
92 is \ 93 is ] 94 is ^ 95 is _ 96 is ` 97 is a 98 is b 99 is c 100 is d 101 is e
102 is f 103 is g 104 is h 105 is i 106 is j 107 is k 108 is l 109 is m 110 is n 111 is o
112 is p 113 is q 114 is r 115 is s 116 is t 117 is u 118 is v 119 is w 120 is x 121 is y
122 is z 123 is { 124 is | 125 is } 126 is ~ 127 is None
I am struggling in one of the Pattern matching problems in Python
When input = 3, below is the expected output (input value is the number of columns it should print)
Expected output:
1
2 6
3 7 9
4 8
5
I am somehow moving in a wrong direction, hence would need some help in it.
This is the code I have tried so far:
def display():
n = 5
i = 1
# Outer loop for how many lines we want to print
while(i<=n):
k = i
j = 1
# Inner loop for printing natural number
while(j <= i):
print (k,end=" ")
# Logic to print natural value column-wise
k = k + n - j
j = j + 1
print("\r")
i = i + 1
#Driver code
display()
But it is giving me output as this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Anybody who can help me with this?
n=10
for i in range(1,2*n):
k=i
for j in range(2*n-i if i>n else i):
print(k,end=' ')
k = k + 2*n - 2*j - 2
print()
Result
1
2 20
3 21 37
4 22 38 52
5 23 39 53 65
6 24 40 54 66 76
7 25 41 55 67 77 85
8 26 42 56 68 78 86 92
9 27 43 57 69 79 87 93 97
10 28 44 58 70 80 88 94 98 100
11 29 45 59 71 81 89 95 99
12 30 46 60 72 82 90 96
13 31 47 61 73 83 91
14 32 48 62 74 84
15 33 49 63 75
16 34 50 64
17 35 51
18 36
19
>
Here's a way, I started from scratch and not for code, much more easy for me
def build(nb_cols):
values = list(range(1, nb_cols ** 2 + 1))
res = []
for idx in range(nb_cols):
row_values, values = values[-(idx * 2 + 1):], values[:-(idx * 2 + 1)]
res.append([' '] * (nb_cols - idx - 1) + row_values + [' '] * (nb_cols - idx - 1))
for r in zip(*reversed(res)):
print(" ".join(map(str, r)))
Here's a recursive solution:
def col_counter(start, end):
yield start
if start < end:
yield from col_counter(start+1, end)
yield start
def row_generator(start, col, N, i=1):
if i < col:
start = start + 2*(N - i)
yield start
yield from row_generator(start, col, N, i+1)
def display(N):
for i, col_num in enumerate(col_counter(1, N), 1):
print(i, *row_generator(i, col_num, N))
Output:
>>> display(3)
1
2 6
3 7 9
4 8
5
>>> display(4)
1
2 8
3 9 13
4 10 14 16
5 11 15
6 12
7
>>> display(10)
1
2 20
3 21 37
4 22 38 52
5 23 39 53 65
6 24 40 54 66 76
7 25 41 55 67 77 85
8 26 42 56 68 78 86 92
9 27 43 57 69 79 87 93 97
10 28 44 58 70 80 88 94 98 100
11 29 45 59 71 81 89 95 99
12 30 46 60 72 82 90 96
13 31 47 61 73 83 91
14 32 48 62 74 84
15 33 49 63 75
16 34 50 64
17 35 51
18 36
19
Here is the solution using simple loops
def display(n):
nrow = 2*n -1 #Number of rows
i = 1
noofcols = 1 #Number of columns in each row
t = 1
while (i <= nrow):
print(i,end=' ')
if i <= n:
noofcols = i
else:
noofcols = 2*n - i
m =i
if t < noofcols:
for x in range(1,noofcols):
m = nrow + m -(2*x-1)
print(m, end=' ')
i = i+1
print()
I've been struggling to get something to work for the following text file format.
My overall goal is to extract the value for one of the variable names throughout the entire text file. For example, I want all the values for B rows and D rows. Then put them in a normal numpy array and run calculations.
Here is what the data file looks like:
[SECTION1a]
[a] 1424457484310
[b] 5313402937
[c] 873348378938
[d] 882992596992
[e] 14957596088
[SECTION1b]
243 62 184 145 250 180 106 208 248 87 186 137 127 204 18 142 37 67 36 72 48 204 255 30 243 78 44 121 112 139 76 71 131 50 118 10 42 8 67 4 98 110 37 5 208 104 56 55 225 56 0 102 0 21 0 156 0 174 255 171 0 42 0 233 0 50 0 254 0 245 255 110
[END SECTION1]
[SECTION2a]
[a] 1424457484310
[b] 5313402937
[c] 873348378938
[d] 882992596992
[e] 14957596088
[SECTION2b]
243 62 184 145 250 180 106 208 248 87 186 137 127 204 18 142 37 67 36 72 48 204 255 30 243 78 44 121 112 139 76 71 131 50 118 10 42 8 67 4 98 110 37 5 208 104 56 55 225 56 0 102 0 21 0 156 0 174 255 171 0 42 0 233 0 50 0 254 0 245 255 110
[END SECTION2]
That pattern continues for N sections.
Currently I read the file and put it into two columns:
filename_load = fileopenbox(msg=None, title='Load Data File',
default="Z:\*",
filetypes=None)
col1_data = np.genfromtxt(filename_load, skip_header=1, dtype=None,
usecols=(0,), usemask=True, invalid_raise=False)
col2_data = np.genfromtxt(filename_load, skip_header=1, dtype=None,
usecols=(1,), usemask=True, invalid_raise=False)
I was going to then use where, to find the index of the value I wanted, then make a new array of those values:
arr_index = np.where(col1_data == '[b]')
new_array = col2_data[arr_index]
Problem with that is, I end up with arrays of two different sizes because of the weird file format so obviously the data in the array won't match up properly to the right variable name.
I have tried a few other alternatives and get stuck due to the weird text file format and how to read it into python.
Not sure if I should stay on this track an if so how to address the problem, or, try a totally different approach.
Thanks in advance!
A possible solution sorting your data into hierachy of OrdedDict() dictionaries:
from collections import OrderedDict
import re
ss = """[SECTION1a]
[a] 1424457484310
[b] 5313402937
[c] 873348378938
[d] 882992596992
[e] 14957596088
[SECTION1b]
243 62 184 145 250 180 106 208 248 87 186 137 127 204 18 142 37 67 36 72 48 204 255 30 243 78 44 121 112 139 76 71 131 50 118 10 42 8 67 4 98 110 37 5 208 104 56 55 225 56 0 102 0 21 0 156 0 174 255 171 0 42 0 233 0 50 0 254 0 245 255 110
[END SECTION1]
[SECTION2a]
[a] 1424457484310
[b] 5313402937
[c] 873348378938
[d] 882992596992
[e] 14957596088
[SECTION2b]
243 62 184 145 250 180 106 208 248 87 186 137 127 204 18 142 37 67 36 72 48 204 255 30 243 78 44 121 112 139 76 71 131 50 118 10 42 8 67 4 98 110 37 5 208 104 56 55 225 56 0 102 0 21 0 156 0 174 255 171 0 42 0 233 0 50 0 254 0 245 255 110
[END SECTION2]"""
# regular expressions for matching SECTIONs
p1 = re.compile("^\[SECTION[0-9]+a\]")
p2 = re.compile("^\[SECTION[0-9]+b\]")
p3 = re.compile("^\[END SECTION[0-9]+\]")
def parse(ss):
""" Make hierachial dict from string """
ll, l_cnt = ss.splitlines(), 0
d = OrderedDict()
while l_cnt < len(ll): # iterate through lines
l = ll[l_cnt].strip()
if p1.match(l): # new sub dict for [SECTION*a]
dd, nn = OrderedDict(), l[1:-1]
l_cnt += 1
while (p2.match(ll[l_cnt].strip()) is None and
p3.match(ll[l_cnt].strip()) is None):
ww = ll[l_cnt].split()
dd[ww[0][1:-1]] = int(ww[1])
l_cnt += 1
d[nn] = dd
elif p2.match(l): # array of ints for [SECTION*b]
d[l[1:-1]] = [int(w) for w in ll[l_cnt+1].split()]
l_cnt += 2
elif p3.match(l):
l_cnt += 1
return d
dd = parse(ss)
Note that you can get much more robust code, if you use an existing parsing tool (e.g., Parsley).
To retrieve'[c]' from all sections, do:
print("All entries for [c]: ", end="")
cc = [d['c'] for s,d in dd.items() if s.endswith('a')]
print(", ".join(["{}".format(c) for c in cc]))
# Gives: All entries for [c]: 873348378938, 873348378938
Or you could traverse the whole dictionary:
def print_recdicts(d, tbw=0):
"""print the hierachial dict """
for k,v in d.items():
if type(v) is OrderedDict:
print(" "*tbw + "* {}:".format(k))
print_recdicts(v, tbw+2)
else:
print(" "*tbw + "* {}: {}".format(k,v))
print_recdicts(dd)
# Gives:
# * SECTION1a:
# * a: 1424457484310
# * b: 5313402937
# ...
The following should do it. It uses a running store (tally) to cope with missing values, then writes the state out when hitting the end marker.
import re
import numpy as np
filename = "yourfilenamehere.txt"
# [e] 14957596088
match_line_re = re.compile(r"^\[([a-z])\]\W(\d*)")
result = {
'b':[],
'd':[],
}
tally_empty = dict( zip( result.keys(), [np.nan] * len(result) ) )
tally = tally_empty
with open(filename, 'r') as f:
for line in f:
if line.startswith('[END SECTION'):
# Write accumulated data to the lists
for k, v in tally.items():
result[k].append(v)
tally = tally_empty
else:
# Map the items using regex
m = match_line_re.search(line)
if m:
k, v = m.group(1), m.group(2)
print(k,v)
if k in tally:
tally[k] = v
b = np.array(result['b'])
d = np.array(result['d'])
Note, whatever keys are in the result dict definition will be in the output.
How do i use a loop nested within a loop to create this output:
100
101 102
103 104 105
106 107 108 109
You can do this using a while loop with certain other variables:
>>> st, end, length = 100, 110, 1
>>> while st < end:
... print (" ".join(map(lambda x: "%3d" % x, range(st,st+length))))
... st += length
... length += 1
...
100
101 102
103 104 105
106 107 108 109
Note that I have used a lambda instead of str in the map, this is so that different width numbers don't break up the indentation.
You can similarly base this on the width of the final line as below (in which case there is no need to keep track of the end variable I was doing above):
>>> st, width = 1, 1
>>> while width <= 15:
... print (" ".join(map(lambda x: "%3d" % x, range(st, st + width))))
... st += width
... width += 1
...
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 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91
92 93 94 95 96 97 98 99 100 101 102 103 104 105
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
Something like this???
start = 100
lines = 5
for i in range(lines):
stop = start + i + 1
for j in range(a, stop):
print j,
start = stop
print
Just use two-level for loop:
x = 100
for i in range(1, 5):
for j in range(i):
print(x, end=" ")
x += 1
print("")
I need to write a program that gives an output of the following table:
chr: ! " # $ % & ' ( ) * + , - . /
asc: 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
chr: 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
asc: 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
chr: # A B C D E F G H I J K L M N O
asc: 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
chr: P Q R S T U V W X Y Z [ \ ] ^ _
asc: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
chr: ` a b c d e f g h i j k l m n o
asc: 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
chr: p q r s t u v w x y z { | } ~
asc: 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
Any help would be appreciated, though I would like to ask to not be given the entire answer, but rather hints, so there is some challenge involved for me. Thanks.
The ord and chr functions will help you out:
ord('a') # 97
chr(97) # 'a'
Add to a range, and you got a stew going on!
for i in range(32,128):
print (i, chr(i))
or to be even closer to what you want:
#!/usr/bin/python3
def f(x,y):
for i in range(x,y):
print ('%3d '%i,end=''),
print()
for i in range(x,y):
print ('%3s '%chr(i),end='')
print()
for x in range(32,128,16):
f(x,x+16)
print '''chr: ! " # $ % & ' ( ) * + , - . /
asc: 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
chr: 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
asc: 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
chr: # A B C D E F G H I J K L M N O
asc: 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
chr: P Q R S T U V W X Y Z [ \ ] ^ _
asc: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
chr: ` a b c d e f g h i j k l m n o
asc: 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
chr: p q r s t u v w x y z { | } ~
asc: 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127'''
Hint: use loops in the loops with given range thus distinguishing lines as cases. The converted characters may be added as strings together and you only print the line after you have all strings added.
The full code would be:
for i in range (2,14):
#range(1,13 would have been correct as well, but I want to use the parity)
if i%2==0: #use even numbers for "chr..." line
a="chr: "
for j in range(int((i/2-1)*16+32),int((i/2-1)*16+48)):
#range is a bit complicated due to the i-range
b=str(chr(j))
#the following ifs are used to regulate space depending on character length
if len(b)==1:
s=" "
if len(b)==2:
s=" "
if len(b)==3:
s=" "
a=a+b+s #add new characters with space to the previous ones
print(a)
if i%2==1: #use odd numbers for asc:... line
a="asc: "
for j in range(int(((i-1)/2-1)*16+32),int(((i-1)/2-1)*16+48)):
b=str(j) #in this line you need only the numbers
#the following ifs are used to regulate space depending on character length
if len(b)==1:
s=" "
if len(b)==2:
s=" "
if len(b)==3:
s=" "
a=a+b+s
print(a)
A good friend gave me this tip, and it works! The remaining thing to do is to adjust placeholders:
for i in range (0, 12):
if i%2 ==0:
content ="chr:"
for j in range (32, 48):
content=content+" "+str(chr(j+(i//2)*16))
print (content)
if i%2 ==1:
content = "asc:"
for j in range (32, 48):
content=content+" "+str(j+(i//2)*16)
print (content)
Forgive me as I am just beginning but the following worked for me:
i=32
while i <= 112:
print ('chr:\t'+chr(i)+'\t'+chr(i+1)+'\t'+chr(i+2)+'\t'+chr(i+3)+'\t'+chr(i+4)+'\t'+chr(i+5)+'\t'+chr(i+6)+'\t'+chr(i+7)+'\t'+chr(i+8)+'\t'+chr(i+9)+'\t'+chr(i+10)+'\t'+chr(i+11)+'\t'+chr(i+12)+'\t'+chr(i+13)+'\t'+chr(i+14)+'\t'+chr(i+15))
print ('asc:\t'+str(i)+'\t'+str(i+1)+'\t'+str(i+2)+'\t'+str(i+3)+'\t'+str(i+4)+'\t'+str(i+5)+'\t'+str(i+6)+'\t'+str(i+7)+'\t'+str(i+8)+'\t'+str(i+9)+'\t'+str(i+10)+'\t'+str(i+11)+'\t'+str(i+12)+'\t'+str(i+13)+'\t'+str(i+14)+'\t'+str(i+15))
i=i+16
Now I am just trying to create a second loop to take care of the progression/iteration