Using generator to fill integer values in 2-D array - python-3.x

I want to use the below code (am supposed to not use map(), for an online programming site as gives error on that of : TypeError: 'map' object is not subscriptable
):
arr[i][j] = [int(input("Input score").strip().split()[:l]) for j in range(n) for i in range(t)]
instead of the below working version:
for i in range(t):
for j in range(n):
arr[i][j] = map(int, input("Input score").strip().split())[:l]
but the error is (assume so) based on providing a list instead of individual values, as stated below:
TypeError: int() argument must be a string or a number, not 'list'
Unable to find a solution by any alternate way, say convert rhs (of desired soln.) to a string in first step & then assign to lhs in the second step; as need assign to arr[i][j].
P.S. Need to make the solution use the individual and row-wise values of arr, as say need find row-wise sum of values or even individual values. The below code uses the row-wise arr values to fill up total.
for i in range(t):
for j in range(n):
# Find sum of all scores row-wise
sum = 0
for m in arr[i][j]:
sum += m
total[i][j] = sum

You can map your nested for loops:
for i in range(t):
for j in range(n):
arr[i][j] = map(int, input("Input score").strip().split())[:l]
to a list comprehension like:
arr = [map(int, input("Input score").strip().split())[:l] for i in range(t) for j in range(n)]
And without a map like:
arr = [[int(k) for k in input("Input score").strip().split())[:l]]
for i in range(t) for j in range(n)]

We can do a nested list comprehension as follows:
t = int(input("Input number of tests: "))
n = int(input("Input number of rows: "))#.strip().split())
total = [[sum([int(i) for i in input("Input score: ").split()]) for j in range(n)] for t_index in range(t)]
print(total)
Example of an input-output pair:
Input number of tests: 2
Input number of rows: 3
Input score: 1 2 3
Input score: 2 3 4
Input score: 3 4 5
Input score: 4 5 6
Input score: 5 6 7
Input score: 6 7 8
[[6, 9, 12], [15, 18, 21]]

Related

How many times should I loop to cover all cases of possible sums?

I am trying to solve this competitive programming problem using python3. The problem asks, given an array of size n, split the array into three consecutive, contiguous parts such that the first part has maximum sum and equals the sum of the third part. The elements in the array are positive integers.
My approach:
inputN = int(input())
inputString = input()
usableString = stringToList(inputString)
counting = 0
sum1 = usableString[0]
sum3 = usableString[-1]
maxSum1 = 0
countFromLeft = 1
countFromRight = 2
while counting < inputN-1:
if sum1 > sum3:
sum3 += usableString[-countFromRight]
countFromRight += 1
elif sum3 > sum1:
sum1 += usableString[countFromLeft]
countFromLeft += 1
elif sum1 == sum3:
maxSum1 = sum1
sum1 += usableString[countFromLeft]
countFromLeft += 1
counting += 1
print(maxSum1)
We read in the array elements and store them in a list usableString.
We set two variables sum1 and sum3 to the first and last elements of the list respectively.
We set a variable to keep track of the maximum sum of the first part of the list.
Finally, we set a variable counting to 0 which will represent the number of elements we have added from the list into sum1 or sum3.
The rest of the logic is in the while loop, which just checks if sum1 is larger than sum3 or the other way around and otherwise if they equal. After each iteration we add 1 to counting as an extra element has been included in a part. The while loop should stop when the number of elements used (i.e counting) is equal to the number of elements in the array - 1, since we added the first and last elements before entering the loop, which makes (array - 2), however, we still need to loop one additional time to check if sum1 and sum3 are equal.
I checked your submitted algorithm, and the problem is your stringToList function:
def stringToList(s):
list=[]
for elem in s:
if elem != " ":
list.append(int(elem))
return list
As far as I can tell, your main algorithm is completely fine, but stringToList does one crucial thing incorrectly:
>>> stringToList('2 4 6 8 10')
[2, 4, 6, 8, 1, 0]
# should be
[2, 4, 6, 8, 10]
As it treats each character individually, the two digits of 10 are turned into 1, 0. A simpler method which performs correctly would be to do the following:
# explanation
>>> input()
'2 4 6 8 10'
>>> input().split(' ')
['2', '4', '6', '8', '10']
>>> map(int, input().split(' ')) # applies the int function to all elements
<map object at 0x...>
>>> list(map(int, input().split(' '))) # converts map object into list
[2, 4, 6, 8, 10]
Sorry it took so long, I ended up making my own algorithm to compare to yours, ran my own tests, and then ran your code with the input to list method I just explained, and figured the only difference was your stringToList function. Took a while, but I hope it helps!
Just for the fun, here's my algorithm and turns out it was pretty similar to yours!
array = [1, 3, 2, 1, 4]
n = len(array)
slice = [0, n]
sum = [array[0], 0]
bestSum = 0
while slice[0] < slice[1]-1:
i = 0 if (sum[0] < sum[1]) else 1
slice[i] += 1-(2*i)
sum[i] += array[slice[i]]
if sum[0] == sum[1]: bestSum = sum[0]
# print(array[ : slice[0]+1], array[slice[0]+1 : slice[1]], array[slice[1] : ])
print(bestSum)

Writing a function that calculates the average value of 5 parameters from user input

I need to build a code that will give the average sum of 5 user input parameters. I have to add all 5 parameters, and then divide the addition by 5. I also have to make sure the function uses the return command to return the average as the value for the function. Since I am a beginner I can't use advanced code. Been stuck for days.
I have tried converting the string into an int
I have tried converting a list to a string to an int
I have tried making multiple variables.
from statistics import mean
a = input("Enter 1st number:")
b = input("Enter 2nd number:")
c = input("Enter 3rd number:")
d = input("Enter 4th number:")
e = input("Enter 5th number:")
inputs = ['a', 'b', 'c', 'd', 'e']
input1 = int(inputs)
mean(inputs)
import math
a = input("Enter 1st number:")
b = input("Enter 2nd number:")
c = input("Enter 3rd number:")
d = input("Enter 4th number:")
e = input("Enter 5th number:")
inputs = ['a', 'b', 'c', 'd', 'e']
avg_mean = "5"
totals = int(inputs) / avg_mean
I expect to get all 5 user input numbers and divide it by 5 to get the average sum.
You have a number of issues, I will point a few out for you:
from statistics import mean
a = input("Enter 1st number:")
b = input("Enter 2nd number:")
c = input("Enter 3rd number:")
d = input("Enter 4th number:")
e = input("Enter 5th number:")
Up to this point you are OK, you could store these inputs better and use a loop instead of copy pasting 5 times but this will still give you what you want
inputs = ['a', 'b', 'c', 'd', 'e']
The above line is not doing what I imagine you want. If you want to put your 5 values into a list you need to use the variables a,b,c,d,e instead of the characters 'a','b','c','d','e'
inputs = [a, b, c, d, e]
Next up, int() does not work on lists as a whole, you need to pass 1 string at a time. here's a simple way to do this:
for i in range(5):
inputs[i] = int(inputs[i])
Then, mean will work as you want with the integer inputs list
mean(inputs)
Finally, you mention wanting to turn this into a function, once everything is working, turning it into a function with a return value is quite easy. I'll leave that up to your research
A pythonic implementation
Create input directly into a list and repeat with range
There's no need to create a separate object for each input
There's no need to then load those 5 objects into another object
Convert input to int immediately with int(input())
statistics.mean works on the entire list
[x for x in range(5)] is a list comprehension
f'Input {x} values' is an f-String
The function accepts a parameter for how many inputs. The default is 5, but that isn't used if you pass some other number when the function is called.
from statistics import mean
def mean_of_inputs(number_of_inputs: int=5) -> float:
return mean([int(input(f'Please input {x + 1} of {number_of_inputs} numbers: ')) for x in range(number_of_inputs)])
# Use the function
mean_of_inputs(6)
Please input 1 of 6 numbers: 10
Please input 2 of 6 numbers: 20
Please input 3 of 6 numbers: 30
Please input 4 of 6 numbers: 40
Please input 5 of 6 numbers: 50
Please input 6 of 6 numbers: 60
35
Alternative 1:
No list comprehension
No imported modules
Stores all the inputs in numbers and uses the built-in function, sum
def mean_of_inputs(number_of_inputs: int=5) -> float:
numbers = list()
for x in range(number_of_inputs):
numbers.append(int(input(f'Please input {x + 1} of {number_of_inputs} numbers: ')))
return sum(numbers) / number_of_inputs
Call the function:
mean_of_inputs()
Please input 1 of 5 numbers: 2
Please input 2 of 5 numbers: 4
Please input 3 of 5 numbers: 6
Please input 4 of 5 numbers: 8
Please input 5 of 5 numbers: 10
6.0
Alternative 2:
Don't store the inputs, just add them to a running total
def mean_of_inputs(number_of_inputs: int=5) -> float:
sum_of_inputs = 0
for x in range(number_of_inputs):
sum_of_inputs += int(input(f'Please input {x + 1} of {number_of_inputs} numbers: '))
return sum_of_inputs / number_of_inputs
from statistics import mean
a = input("Enter 1st number:")
b = input("Enter 2nd number:")
c = input("Enter 3rd number:")
d = input("Enter 4th number:")
e = input("Enter 5th number:")
m = mean(map(int, [a,b,c,d,e]))

Unable to assign result of map() to 2-D list

The below code is for taking a set of rows of students' marks in array, and need find the row with maximum marks.
Below is incomplete code, as need to search for the maximum sum row still; but stuck at the incomplete code due to error.
It gives below error in py3.codeskulptor.org/, while in Pythontutor, the program terminates at the same line number.
Line #17: IndexError: list assignment index out of range
# Input number of tests
t = int(input("Input number of tests"))
# Input size of rows (of students)
n = int(input("Input size of rows"))#.strip().split())
print (t,n)
arr = [[[] for i in range(t)] for i in range(n)]
total = [[] for i in range (n)]
for i in range(0,t):
# Input score of each student in row
sum =0
for j in range(n):
arr[i][j] = map(int, input("Input score").strip().split())#[:n]
#the above line causes compilation error
# Find sum of all scores row-wise
for m in arr[i][j]:
sum += m
total[i] = sum1
# Find the max. of total
for j in range(t):
y = max(total[j])
Please also suggest a crisper approach to program the above problem.
P.S. I found the above code to be nearly wrong, but kicked me in correct direction.
Have the modified code below with a question that arose during debugging that concerns the :
max() giving precedence to [] over an integer value
This behaviour of max() was detected when incorrectly stated line #13 as :
total = [[[] for i in range (l)] for i in range (n)]
The correct working code is below, with output :
# Input number of tests
t = int(input("Input number of tests"))
# Input number of rows (of students)
n = int(input("Input number of rows"))#.strip().split())
# Input limit on number of students in a row (of students)
l = int(input("Input max. number of studentsin any row"))#.strip().split())
print ('t :',t,'n :',n, 'l :', l)
arr = [[[[] for i in range(l)] for i in range(n)] for i in range(t)]
total = [[[] for i in range (n)] for i in range (t)]
# run input of tests
for i in range(t):
# Input score of each student in the i-th row, out of n
sum =0
for j in range(n):
#for k in range(l):
print("jkl:","i:",i,"j:",j)
arr[i][j] = map(int, input("Input score").strip().split())[:l]
for i in range(t):
for j in range(n):
# Find sum of all scores row-wise
sum = 0
for m in arr[i][j]:
#sum[i][j][] += m
print ('m :', m)
sum += m
#total[i][j] = sum[i][j][]
total[i][j] = sum
for i in range(t):
print("Test no. ", i)
for j in range(n):
#for m in arr[i][j]:
print (arr[i][j])
#print (m)
print("=========")
for i in range(t):
for j in range(n):
print(i,"-",j, total[i][j])
print("::::::")
print("=========")
# Find the max. of total
for i in range(t):
print([m for m in total[i]])
y = max([m for m in total[i]])
print ('i:',i,',', 'max total:',y)
Request reason for the precedence shown by max(), and if possible link the answer with some reference to underlying implementation in CPython.
arr = [[[] for i in range(t)] for i in range(n)]
Considering the above construction of arr, you have swapped t and n in the nested loops:
for i in range(t):
# …
for j in range(n):
arr[i][j] = …
The first index into arr (corresponding to the outer loop) must be a number between 0 and n–1.
The second index into arr (corresponding to the inner loop) must be a number between 0 and t–1.
You are making a mistake between t and n
i should be in range(n)
and j should be in range(t)

Making a matrix in python 3 without numpy using inputs

I want to have two inputs : a,b or x,y whatever...
When the user inputs say,
3 5
Then the shell should print a matrix with 3 rows and 5 columns also it should fill the matrix with natural numbers( number sequence starting with 1 and not 0).
Example::
IN :2 2
OUT:[1,2]
[3,4]
If your objective is only to get the output in that format
n,m=map(int,input().split())
count=0
for _ in range(0,n):
list=[]
while len(list) > 0 : list.pop()
for i in range(count,count+m):
list.append(i)
count+=1
print(list)
I am going to give a try without using numpy library.
row= int(input("Enter number of rows"))
col= int(input("Enter number of columns"))
count= 1
final_matrix= []
for i in range(row):
sub_matrix= []
for j in range(col):
sub_matrix.append(count)
count += 1
final_matrix.append(sub_matrix)
Numpy library provides reshape() function that does exactly what you're looking for.
from numpy import * #import numpy, you can install it with pip
n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = range(1, n*m+1) #You want the range to start from 1, so you pass that as first argument.
x = reshape(x,(n,m)) #call reshape function from numpy
print(x) #finally show it on screen
EDIT
If you don't want to use numpy as you pointed out in the comments, here's another way to solve the problem without any libraries.
n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = 1 #You want the range to start from 1
list_of_lists = [] #create a lists to store your columns
for row in range(n):
inner_list = [] #create the column
for col in range(m):
inner_list.append(x) #add the x element and increase its value
x=x+1
list_of_lists.append(inner_list) #add it
for internalList in list_of_lists: #this is just formatting.
print(str(internalList)+"\n")

Cumulative total from user's input string

I have tried to write a function that takes sequence of integers as input from the user and returns cumulative totals. For example, if the input is 1 7 2 9, the function should print 1 8 10 19. My program isn't working. Here is the code:
x=input("ENTER NUMBERS: ")
total = 0
for v in x:
total = total + v
print(total)
and here is the output:
ENTER NUMBERS: 1 2 3 4
Traceback (most recent call last):
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module>
total = total + v
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I don't know what this error means. Please help me to debug my code.
This code will work. Remember: read the code and learn how it works.
x = input("Enter numbers: ") #Take input from the user
list = x.split(" ") #Split it into a list, where
#a space is the separator
total = 0 #Set total to 0
for v in list: #For each list item
total += int(v) #See below for explanation
print(total) #Print the total so far
There are two new things in this code:
x.split(y) splits x up into a list of smaller strings, using y as the separator. For example, "1 7 2 9".split(" ") returns ["1", "7", "2", "9"].
total += int(v) is more complicated. I'll break it down more:
The split() function gave us an array of strings, but we want numbers. The int() function (among other things) converts a string to a number. That way, we can add it.
The += operator means "increment by". Writing x += y is the same as writing x = x + y but takes less time to type.
There is another problem with the code: You say you need a function, but this is not a function. A function might look like this:
function cumulative(list):
total = 0
outlist = []
for v in list:
total += int(v)
outlist.append(total)
return outlist
and to use it:
x = input("Enter numbers: ").split(" ")
output = cumulative(x)
print(output)
but the program will work just fine.
Cumulative totals
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
sum = 0
new_list=[]
for i in range(len(input_set)):
sum = sum + input_set[i]
new_list.append(sum)
print(new_list)

Resources