Third line of input not read - python

Why doesn't it read the third line of input
This is the code that is written in python3. Not much explanation is required as it's very basic programming.
n, x = list(map(int, input().split(" ")))
s = []
print(x)
for i in range(0,3):
s.append(input())
print(s)
print("hello")
Input is :
5 3
89 90 78 93 80
90 91 85 88 86
91 92 83 89 90.5
Output I got:
3
['89 90 78 93 80']
['89 90 78 93 80', '90 91 85 88 86']

You need an additional newline character at the end of your input so that input() would recognize the last line as a line.

I changed the .split(" ") to .split() and got the output.

Related

How to iterate and print each element in list (Python)

arr(['36 36 30','47 96 90','86 86 86']
I want to store and print the values like this,
36
36
30
47
...
How do I do this using python?
the simplest way is to use for and str.split()
arr=['36 36 30','47 96 90','86 86 86']
for block in arr:
cells = block.split()
for cell in cells:
print(cell)
prints
36
36
30
47
96
90
86
86
86
you can also use a list comprehension like so, which returns the same result.
print("\n".join([ele for block in arr for ele in block.split()]))
You can use lists and split in python. Try in this way:
arr = ['36 36 30','47 96 90','86 86 86']
for i in arr:
elems = i.split()
for elem in elems:
print(elem)
We can try the following approach. Build a single string of space separated numbers, split it, then join on newline.
inp = ['36 36 30', '47 96 90', '86 86 86']
output = '\n'.join(' '.join(inp).split())
print(output)
This prints:
36
36
30
47
96
90
86
86
86

How to do kernel function on an array of strings in Numba cuda?

I have an array of strings that i read from file ,i want to compare each line of my file to a specific string..the file is too large (about 200 MB of lines)
i have followed this tutorial https://nyu-cds.github.io/python-numba/05-cuda/ but it doesn't show exactly how to deal with array of strings/characters.
import numpy as np
from numba import cuda
#cuda.jit
def my_kernel(io_array):
tx = cuda.threadIdx.x
ty = cuda.blockIdx.x
bw = cuda.blockDim.x
pos = tx + ty * bw
if pos < io_array.size: # Check array boundaries
io_array[pos] # i want here to compare each line of the string array to a specific line
def main():
a = open("test.txt", 'r') # open file in read mode
print("the file contains:")
data = country = np.array(a.read())
# Set the number of threads in a block
threadsperblock = 32
# Calculate the number of thread blocks in the grid
blockspergrid = (data.size + (threadsperblock - 1)) // threadsperblock
# Now start the kernel
my_kernel[blockspergrid, threadsperblock](data)
# Print the result
print(data)
if __name__ == '__main__':
main()
I have two problems.
First: how to send my sentence (string) that i want to compare each line of my file to it to the kernal function. (in the io_array without affecting the threads computation)
Second: it how to deal with string array? i get this error when i run the above code
this error is usually caused by passing an argument of a type that is unsupported by the named function.
[1] During: typing of intrinsic-call at test2.py (18)
File "test2.py", line 18:
def my_kernel(io_array):
<source elided>
if pos < io_array.size: # Check array boundaries
io_array[pos] # do the computation
P.S i'm new to Cuda and have just started learning it.
First of all this:
data = country = np.array(a.read())
doesn't do what you think it does. It does not yield a numpy array that you can index like this:
io_array[pos]
If you don't believe me, just try that in ordinary python code with something like:
print(data[0])
and you'll get an error. If you want help with that, just ask your question on the python or numpy tag.
So we need a different method to load the string data from disk. For simplicity, I choose to use numpy.fromfile(). This method will require that all lines in your file are of the same width. I like that concept. There's more information you would have to describe if you want to handle lines of varying lengths.
If we start out that way, we can load the data as an array of bytes, and use that:
$ cat test.txt
the quick brown fox.............
jumped over the lazy dog........
repeatedly......................
$ cat t43.py
import numpy as np
from numba import cuda
#cuda.jit
def my_kernel(str_array, check_str, length, lines, result):
col,line = cuda.grid(2)
pos = (line*(length+1))+col
if col < length and line < lines: # Check array boundaries
if str_array[pos] != check_str[col]:
result[line] = 0
def main():
a = np.fromfile("test.txt", dtype=np.byte)
print("the file contains:")
print(a)
print("array length is:")
print(a.shape[0])
print("the check string is:")
b = a[33:65]
print(b)
i = 0
while a[i] != 10:
i=i+1
line_length = i
print("line length is:")
print(line_length)
print("number of lines is:")
line_count = a.shape[0]/(line_length+1)
print(line_count)
res = np.ones(line_count)
# Set the number of threads in a block
threadsperblock = (32,32)
# Calculate the number of thread blocks in the grid
blocks_x = (line_length/32)+1
blocks_y = (line_count/32)+1
blockspergrid = (blocks_x,blocks_y)
# Now start the kernel
my_kernel[blockspergrid, threadsperblock](a, b, line_length, line_count, res)
# Print the result
print("matching lines (match = 1):")
print(res)
if __name__ == '__main__':
main()
$ python t43.py
the file contains:
[116 104 101 32 113 117 105 99 107 32 98 114 111 119 110 32 102 111
120 46 46 46 46 46 46 46 46 46 46 46 46 46 10 106 117 109
112 101 100 32 111 118 101 114 32 116 104 101 32 108 97 122 121 32
100 111 103 46 46 46 46 46 46 46 46 10 114 101 112 101 97 116
101 100 108 121 46 46 46 46 46 46 46 46 46 46 46 46 46 46
46 46 46 46 46 46 46 46 10]
array length is:
99
the check string is:
[106 117 109 112 101 100 32 111 118 101 114 32 116 104 101 32 108 97
122 121 32 100 111 103 46 46 46 46 46 46 46 46]
line length is:
32
number of lines is:
3
matching lines (match = 1):
[ 0. 1. 0.]
$

How do i convert a string of ascii values to there original character/number in python

i have a string with numbers that i previously converted with my encoder but now i am trying to decode it ive searched around and no answers seem to work
if you have any i dear how to do this then let me know
string = 91 39 65 97 66 98 67 99 32 49 50 51 39 93
outcome = ABCabc 123
outcome = "".join([your_decoder.decode(x) for x in string.split(" ")])

python using data from a list, where by you call the data from its index number

I must open a file, compute the averages of a row and column and then the max of the data sheet. The data is imported from a text file. When I am done with the program, it should look like an excel sheet, only printed on my terminal.
Data file must be seven across by six down.
88 90 94 98 100 110 120
75 77 80 86 94 103 113
80 83 85 94 111 111 121
68 71 76 85 96 122 125
77 84 91 102 105 112 119
81 85 90 96 102 109 134
Later, I will have to print the above data. I the math is easy, my problem is selecting the number from the indexed list. Ex:
selecting index 0, 8, 16, 24, 32, 40. Which should be numbers 88, 75, 80, 68, 77, 81.
What I get when I input the index number is 0 = 8, 1 = 8, 2 = " "... ect.
What have I done wrong here? I have another problem where I had typed into the program the list, which works as I wanted this to work. That program was using the index numbers to select a month. 0= a blank index, 1 = january, 2 = Febuary, ect...
I hope this example made clear what I intended to do, but cannot seem to do. Again, the only difference between my months program and this program is that for the below code, I open a file to fill the list. Have I loaded the data poorly? Split and stripped the list poorly? Help is more useful than answers, as I can learn rather than be given the answer.
def main():
print("Program to output a report of noise for certain model cars.")
print("Written by censored.")
print()
fileName = input("Enter the name of the data file: ")
infile = open(fileName, "r")
infileData = infile.read()
line = infileData
#for line in infile:
list = line.split(',')
list = line.strip("\n")
print(list)
n = eval(input("Enter a index number: ", ))
print("The index is", line[n] + ".")
print("{0:>38}".format(str("Speed (MPH)")))
print("{0:>6}".format(str("Car")), ("{0:>3}".format(str(":"))),
("{0:>6}".format(str("30"))), ("{0:>4}".format(str("40"))),
("{0:>4}".format(str("50"))))
main()
Thank you for your time.
You keep overwriting your variables, and I wouldn't recommend masking a built-in (list).
infileData = infile.read()
line = infileData
#for line in infile:
list = line.split(',')
list = line.strip("\n")
should be:
infileData = list(map(int, infile.read().strip().split()))
This reads the file contents into a string, strips off the leading and trailing whitespace, splits it up into a list separated by whitespace, maps each element as an int, and creates a list out of that.
Or:
stringData = infile.read()
stringData = stringData.strip()
stringData = stringData.split()
infileData = []
for item in stringData:
infileData.append(int(item))
Storing each element as an integer lets you easily do calculations on it, such as if item > 65 or exceed = item - 65. When you want to treat them as strings, such as for printing, cast them as such with str():
print("The index is", str(infileData[n]) + ".")
Just to be clear, it looks like your data is space-separated not comma separated. So when you call,
list = line.split(',')
the list looks like this,
['88 90 94 98 100 110 120 75 77 80 86 94 103 113 80 83 85 94 111 111 121 68 71 76 85 96 122 125 77 84 91 102 105 112 119 81 85 90 96 102 109 134']
So therefore, when you access list[0], you will get '8' not '88', or when you access list[2] you will get ' ', not '94'
list = line.split() # this is what you should call (space-separated)
Again this answer is based on how your data is presented.

programming challenge help (python)? [duplicate]

This question already has answers here:
Euler project #18 approach
(10 answers)
Closed 9 years ago.
I'm trying to solve project euler problem 18/67 . I have an attempt but it isn't correct.
tri = '''\
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23'''
sum = 0
spot_index = 0
triarr = list(filter(lambda e: len(e) > 0, [[int(nm) for nm in ln.split()] for ln in tri.split('\n')]))
for i in triarr:
if len(i) == 1:
sum += i[0]
elif len(i) == 2:
spot_index = i.index(max(i))
sum += i[spot_index]
else:
spot_index = i.index(max(i[spot_index],i[spot_index+1]))
sum += i[spot_index]
print(sum)
When I run the program, it is always a little bit off of what the correct sum/output should be. I'm pretty sure that it's an algorithm problem, but I don't know how exactly to fix it or what the best approach to the original problem might be.
Your algorithm is wrong. Consider if there was a large number like 1000000 on the bottom row. Your algorithm might follow a path that doesn't find it at all.
The question hints that this one can be brute forced, but that there is also a more clever way to solve it.
Somehow your algorithm will need to consider all possible pathways/sums.
The brute force method is to try each and every one from top to bottom.
The clever way uses a technique called dynamic programming
Here's the algorithm. I'll let you figure out a way to code it.
Start with the two bottom rows. At each element of the next-to-bottom row, figure out what the sum will be if you reach that element by adding the maximum of the two elements of the bottom row that correspond to the current element of the next-to-bottom row. For instance, given the sample above, the left-most element of the next-to-bottom row is 63, and if you ever reach that element, you will certainly choose its right child 62. So you can replace the 63 on the next-to-bottom row with 63 + 62 = 125. Do the same for each element of the next-to-bottom row; you will get 125, 164, 102, 95, 112, 123, 165, 128, 166, 109, 112, 147, 100, 54. Now delete the bottom row and repeat on the reduced triangle.
There is also a top-down algorithm that is dual to the one given above. I'll let you figure that out, too.

Categories