How to read matrix from stdin(console)? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to read from stdin and the first line specify the dimension of matrix always square matrix
but my code reads only the first line
Example Input
3
0 2 3
2 4 1
3 1 4
My code
def read_matrix(formatted_string):
list_of_lists = [list(map(int, row.split())) for row in formatted_string.split('\n')]
return list_of_lists
x = input("enter the list of lists of numbers?")
print(read_matrix(x))

You're only asking the number of rows but not the content of rows themselves. Following code shows how to generate the full matrix:
def read_matrix(count):
list_of_lists = [list(map(int, input('Enter a row: ').split())) for _ in range(count)]
return list_of_lists
x = input("enter the list of lists of numbers?")
print(read_matrix(int(x)))
It will first query the user the number of rows and pass that number to read_matrix which will ask the user to input every line.

According to the official documentation,
The function then reads a line from input,
converts it to a string (stripping a trailing newline)
Please, note reads a line. But here you are trying to read 4 lines with one call to input. You might want to run a loop to take this input.

Related

How to convert the output into a single line [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
#python
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
rev=arr[::-1]
for i in range(n):
final=0
final+=rev[i]
print(final)
Given an array of integers, print the elements in reverse order as a single line of space-separated numbers.
You are calling input() many times which is not required, also you can use the join function with " " separator to print all the elements of array in one line. Please note that join expects all elements as str so you will have to map it back to str, so it's better to avoid the map to int at the initial stage as we will have to map it back to str
Here is one of the approach:
n = input("Enter the sequence of numbers: ").strip()
arr = n.split()
print (" ".join(arr[::-1]))
Output:
Enter the sequence of numbers: 1 3 5 7 9
9 7 5 3 1
u may use join method for concat string sequences
but in your case u need to transform integers to string type
in the end code will be like this:
reversed_string = ' '.join(map(str, rev))

Read input and return three strings in reverse order (only 1 string so far) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
def rev(one, two, three):
print("Reverse of the third string is",three[::-1])
# returning concatenation of first two strings
return one+two
def main():
# Taking user input of 3 strings
first = input("Enter first string:")
second = input("Enter second string:")
third = input("Enter third string:")
# calling function, passing three arguments
print("Reverse of third string is",rev(first, second, third))
main()
Assignment
Write a Python function that will accept as input three string values
from a user. The method will return to the user a concatenation of the string values in reverse order. The function is to be called from the main method.
In the main method, prompt the user for the three strings.
If the input of the strings is Hello, World, and Car, then the output should be raCdlroWolleH
Your rev function could contain just one line of code (you should call it in the main function). It is as simple as :
return three[::-1]+two[::-1]+one[::-1]
I think the problem is that you're doing two separated prints, one for the first two words and other to the third word. If what you pretende is to join all of the three words and return that, then all you have to do is
New = one + two + three
return New[::-1]

a line of numbers (python) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm not a programmer, I'm just starting to learn python 2.
I wanted to know how can I write a code in python 2 to get an input that consists a line of numbers seperated by space from the user and do operations with each number sepeately and print the output of each number, again, as a line of numbers seperated by space?
The below example will loop complete the action you were looking for, just replace the "+5" with the operation you want
userInput = raw_input("Enter Numbers:")#Get user input
seperateNumbers = userInput.split(" ")#Seperate data based off of spaces
numbersAfterOperations = []#Create a lsi to hold the values after operation applied
for i in range(0, len(seperateNumbers)): #loop throgh all values
numbersAfterOperations.append(int(seperateNumbers[i]) + 5) #add new value
printedValue = ""
for i in range(0, len(numbersAfterOperations)):
printedValue += str(numbersAfterOperations[i]) + " "
print printedValue
You will start with a string containing all your numbers, so you will have something like this:
line_of_num = "0 1 2 3 4 5 6 7 8 9"
You will have to split the elements of this string. You can do it using the split method of the string class, using a space as separator. It will return a list of the items with your numbers, but you can't operate them as integers yet.
list_of_num = line_of_num.split(" ")
You can't operate them yet because the elements of your list are strings. Before operating them, you have to cast them into integers. You can do it using list comprehentions.
list_of_int = [int(element) for element in list_of_num]
Then you can operate them using common operations through elements of a list. Finally, when you have the results, you can return them as a string separated by spaces using the join method of the string class using a space as separator. The join method has as input an iterable (list, for example) of strings.
results = " ".join(["1", "2", "3", "4", "5"])
Your resulted string will be something like "1 2 3 4 5".

How would I create a Python program that reads a list of numbers, and counts how many of them are positive [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need to create a Python program that will count how many positive numbers there are in a list of numbers. The list of numbers has to be typed in by someone. The end result must be the number of elements in the list that were > 0
For an example, this is what you would see on the screen:
>>>Please enter a list of numbers separated by commas: 1,2,-3,-4,5,-6
>>>3
The answer would be 3 in this example. I am sorry if the question seems stupid, but I am a beginner and I am trying my best.
raw_input() for Python 2.x (input() for Python 3) then split() the string at , and then count positive numebers, Example -
s = raw_input("Please enter a list of numbers separated by commas:")
print(len([i for i in s.strip().split(',') if int(i) >= 0]))
You can try like this. input returns tuple
>>> vals = input('get: ')
get: 1,2,-3,-4,5,-6
>>> len([item for item in vals if item > 0])
3
Python 3, input returns string
>>> vals = input('get: ')
get: 1,2,-3,-4,5,-6
>>> len([item for item in vals.split(',') if int(item) > 0])
3
By the way, zero is neither positive nor negative.

sending output values to a new list in python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am doing a project on autonomous vehicle which travels to recommended gps coordinates. How should I create a new list and enter the output values of a program to that list? My program is as below here, I get the line numbers which have have the string $GPRMC. I want to store the line numbers into a list and manipulate those lines further.
f=open('c:\Users\RuthvikWalia\Desktop\gpsdata.txt ','r')
req_lines=0
for line in f:
if(line.find('$GPRMC') >=0 ):
print 'its here', req_lines
req_lines += 1
p=[]
p= p.append(req_lines)
print p
I get the output of only the numbers of lines which have $GPRMC but not the list of numbers of those lines.
This will put tuples of (line_number, line_string) into the list req_lines:
f = open('c:\Users\RuthvikWalia\Desktop\gpsdata.txt ','r')
req_lines = []
for i, line in enumerate(f):
if "$GPRMC" in line:
req_lines.append((i, line))
print req_lines
#Claudiu answer is correct, just to give a small taste of what python's really like, do:
[(idx,line) for idx,line in enumerate(open('gpsdata.txt')) if '$GPRMC' in line]

Categories