printing matrix (2-d) in python - python

I'm trying to print this code into a matrix but keep getting:
line 22, in <module>
print(matrix[i][j], end=" ")
IndexError: list index out of range
This is my code:
A basic code for matrix input from user
R = int(input("Enter the number of runners:"))
C = int(input("Enter the number of days to log:"))
names_runners = []
runners_time =[]
# Initialize matrix
matrix = []
# For user input
for i in range(R): # A for loop for row entries
a = []
names_runners.append(input("enter name of runner" + str(i+1)))
for j in range(C): # A for loop for column entries
runners_time.append(int(input("enter time for day" + str(j+1))))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end=" ")
print()

The first thing that pops out to me is that the number R is never initialized. I don't know if you maybe did this somewhere else in your code, but perhaps make sure that you have a valid value of R.
The second thing I'm noticing is that in the first outer for-loop, you create an empty list a = []... and then don't do anything with it. Make sure you're appending the actual data you care about into the matrix, because right now you're inserting it into unrelated lists and then appending an empty list. Hence, when you try to iterate over as many items as there are in your names_runners and runners_times lists, you end up going out-of-bounds.

I think it would be better to use dictionary in your case, here:
runners_dict = {}
runners_total = 2
days_to_log = int(input("Enter the number of days to log:"))
for i in range(runners_total):
runner_name = input("enter name of runner" + str(i+1))
runners_dict[runner_name] = []
for j in range(days_to_log):
todays_time = int(input("enter time for day" + str(j+1)))
runners_dict[runner_name].append(todays_time)
print(runners_dict)
Results:
Enter the number of days to log:2
enter name of runner1joe
enter time for day1123
enter time for day2321
enter name of runner2bill
enter time for day1123
enter time for day2321
{'joe': [123, 321], 'bill': [123, 321]}

Related

List population

i = int(input('enter number of input: '))
for a in range (0, i):
listInput = int (input("enter your list numbers: "))
List1 = []
List1.append(listInput)
print(List1)
the list only populates the second iteration number not the first input.
include the List1 outside the for loop cuz its getting reinitialized everytime.
Do You want to let user add numbers in a list?
If so, I got a different code snippet
n = int(input("enter number of input: "))
a = list(map(int,input("Enter your list numbers : ").split()))[:n]

How can I find the amount of duplicates an element has within a list?

In this code, I have a user-generated list of numbers and have to find the amount of duplicates a specific element has within that list. I am getting an error in the function. How do I fix this?
def count(list,y):
new_list = []
for j in range(0,x):
if(list[j]==y):
new_list.append(list[j])
else:
pass
print(new_list)
length = len(new_list)
print("The number {} appears {} times in the list".format(y,length))
list = []
x = int(input("Please enter the size of the list you want to create: "))
for i in range(0,x):
value = input("Please enter value of list : ")
list.append(value)
print("The list of the values you entered : {}".format(list))
y = int(input("Which element do you want to find the number? : "))
count(list,y)
There were multiple issues in your code.
In the loop in function count instead j you are using i as index.
initiation of loop index till range(0,x) => x is not defined as the variable is not assigned in this scope, instead use len of the list.
All the inputs added to the list were strings and the one that was searched was an integer.
Other suggestions:
do not use list as a variable name as it is a keyword.
Below this code I am also providing a shorter version of the function count.
def count(mylist,y):
new_mylist = []
for j in range(0,len(mylist)):
print(mylist[j])
if(mylist[j]==y):
new_mylist.append(mylist[i])
else:
pass
length = len(new_mylist)
print("The number {} appears {} times in the mylist".format(y,length))
mylist = []
x = int(input("Please enter the size of the mylist you want to create: "))
for i in range(0,x):
value = int(input("Please enter value of mylist : "))
mylist.append(value)
print("The mylist of the values you entered : {}".format(mylist))
y = int(input("Which element do you want to find the number? : "))
count(mylist,y)
Shorter version
def count(mylist,y):
length = mylist.count(y)
print("The number {} appears {} times in the mylist".format(y,length))
one issue, you're trying to acces the i'th element in list, but i is not initialized. Try replacing i with j
for j in range(0,x):
if(list[i]==y):
new_list.append(list[i])
If you don't mind me taking liberties with your code, here's an example using the Counter from collections. Note that it doesn't do exactly the same thing as your code, as Counter doesn't use indexes as you were using before.
from collections import Counter
input_counter = Counter()
while True:
value = input("Please enter a value (or nothing to finish): ")
if value == '':
break
input_counter[value] += 1
print(input_counter)
y = input("Which number do you want to count the instances of? ")
print(input_counter[y])

How to have a sequence variable within a for loop

def main():
for row in range (7):
assignment = int(1)
if row == 1:
for assignment_number in range(0,8):
assignment_number+1
for i in range(0,7):
assignment_mark = float(input(("Please enter your mark for assginment" assignment_number,": "))
assignment_weight = float(input("Please enter the total weight percentage for the assignment: "))
main()
So this is my code above,
I'm basically trying to work out how I could say for each input variable "Please enter your mark for assignment x (from 1 up to 7).
Which will loop, so once they enter it for assignment 1, it then asks the same question for assignment 2.
I hope this makes some sense. I'm new to programming in general and this just happens to also be my first post on stack! Be gentle (:
Thanks!
There are a few problems with your code:
assignment_number+1 without assigning it to a variable does nothing, and even if you did, that value would be lost after the loop. If you want to offset the numbers by one, you can just use range(1, 8) or do +1 when you actually need that value of that variable
in your second loop, your loop variable is i, but you are using assignment_number from the previous loop, which still has the value from the last execution, 7
you have to store the values for assignments_mark and assignment_weight somewhere, e.g. in two lists, a list of tuples, or a dict of tuples; since assignment numbers start with 1 and not 0, I'd recommend a dict
You can try something like this, storing the marks and weights for the assignments in a dictionary:
assignments = {}
for i in range(7):
assignment_mark = float(input("Please enter your mark for assginment %d: " % (i+1)))
assignment_weight = float(input("Please enter the total weight percentage for the assignment: "))
assignments[i+1] = (assignment_mark, assignment_weight)
print(assignments)
Let the loop do the counting, then use string formatting.
And you only need a single loop to collect each pair of events
from collections import namedtuple
Assignment = namedtuple("Assignment", "mark weight")
assignments = []
for idx in range(7):
print("Please enter data for assignment {}".format(idx+1))
mark = float(input("mark: "))
weight = float(input("weight:"))
assignments.append(Assignment(mark, weight))
print(assignments)

While n > 1. Decrease n by 1 on each iteration

I'm working on some hackerrank problems and I've looked at a couple of ways to take this input and loop through it.
What is be best alternative to trying to decrease n on each iteration as below (as this doesn't seem to be possible).
first_n = int(raw_input())
def findPercentage(n):
if n > 1:
studentinfo = raw_input()
return studentinfo
n = n - 1
result = findPercentage(first_n)
print result
As I'm knew to this, I understand that my logic might be flawed.
The input is passed as stdin with the first line listing the total number of lines to follow. I will want to perform a single operation on every line after the first line with the exception of the last line where I'd look to perform a different operation.
n= int(input())
studentinfo= {}
for i in range(n):
inputs= raw_input().split(" ")
studentinfo[inputs[0]]= inputs[1:];
This will create a dictionary studentinfo with names as key and list of marks as value.
The first line gives you the number of students N:
n = int(raw_input())
Then you want to loop through your function N number of times:
for i in range(n):
studentinfo = raw_input().split(" ")
print(studentinfo[0])
This will create a list called studentinfo, and this will print the student's name. See where you can go from there.

Generating raw_inputs based on user input? [Python]

Is there any way to generate a number of raw_inputs (With unique variables) based on user input? So, say I had this:
if choice == 1:
noelemen = int(raw_input("Enter total amount of elements: "))
Would there be any way to make it so the integer put in that raw_input field would then "generate" the required amount of raw_inputs? I'd suppose, if it was possible, that it'd make use of functions or something similar, but I'm a bit confused about how I'd get it done to be able to do that.
What I have currently is this:
if noelemen == 1:
first = raw_input("Enter element: ")
#Look for the weight of the entered element
weight1 = float(elemen_data.get(first.lower()))
if weight1 is not None:
total_weight = weight1
print "Total mass =", total_weight
if noelemen == 2:
first = raw_input("Enter first element: ")
second = raw_input("Enter second element: ")
#Look for the weight of the entered element
weight1 = float(elemen_data.get(first.lower()))
weight2 = float(elemen_data.get(second.lower()))
if weight1 is not None:
total_weight = weight1 + weight2
print "Total mass =", total_weight
Which is probably a pretty messy way of doing it, particularly as I'd have to go up to perhaps something like 10 elements, or perhaps even beyond.
So, to repeat... Any way to generate raw_inputs with unique variables based on user input?
how about something like this?
elements = []
numberOfPrompts = raw_input("Enter total amount of elements: ")
for i in range(numberOfPrompts):
# will prompt "Enter Element 1: " on the first iteration
userInput = raw_input("Enter Element %s" % (i+1, ))
elements.append(userInput)
Example case:
>>> Enter total amount of elements: 2 # now hit enter
at this point, the value of the variable numberOfPrompts will be 2.
The value of the variable elements will be [], i.e. it is an empty list
>>> Enter Element 1: 3.1415 # hit enter
numberOfPrompts stays 2,
elements will be ['3.1415']
>>> Enter Element 2: 2.7182
elements will be ['3.1415', '2.7182']
Now the for-loop is done and you got your user inputs conveniently in the 0-indexed list elements, which you access like a tuple (array):
>>> elements[1]
2.7182
Edit:
After reading your comment I noticed what you intend to do and, just like the other answer stated, it would be best to use a dictionary for this. This should work:
elements = {}
numberOfPrompts = raw_input("Enter total amount of elements: ")
for i in range(numberOfPrompts):
# will prompt "Enter Element 1: " on the first iteration
userInput = raw_input("Enter Element %s" % (i+1, ))
userInput = userInput.lower()
elements[userInput] = float(elem_data.get(userInput))
now elements will look like this:
{'oxygen':15.9994, 'hydrogen':1.0079}
you can iterate over all keys like this (to find out, which elements have been entered):
for element in elements.keys():
print element
# output:
oxygen
hydrogen
To get all values (to sum them up, for instance), do something like this:
weightSum = 0
for weight in elements.values():
weightSum += weight
print weightSum
# output:
17,0073
Keep in mind that this example is for python 2.x. For python 3.x you will need to adjust a couple of things.
I would use a dictionary for this:
noelemen = int(raw_input("Enter total amount of elements: "))
elem={}
for x in xrange(1,noelemen+1):
elem[x]=raw_input("Enter element: ")

Categories