Making a matrix in python 3 without numpy using inputs - python-3.x

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")

Related

Sum function not working when trying to add numbers in lists using python

I am trying to create a program that takes only even numbers from a range of numbers from 1 to 100 and add all of the even numbers. I am a beginner and I have been trying to get this working since yesterday, and nothing I have tried works. This is my first post, so sorry if the format is wrong but here is my code.
for i in range(1, 100):
if i % 2 == 0:
x = [I]
y = sum(x)
print(y)
The problems with your code has multiple issues that - 1)if you want to get all even numbers from 1 to 100, your range should be (1, 101); 2) the way you build list is wrong (syntax); 3) the sum expect an iterable (list).
There are a few ways to accomplish this sum from 1 to 100 (inclusive), here it will start with yours, and try to show List Comprenshion and Generator Expression way:
lst = [] # to store the build-up list
tot = 0 # to store the answer
for i in range(1, 101):
if i % 2 == 0: # it's a even number
lst.append(i) # store it into lst
tot = sum(lst) # 2550
Generator expression:
all_evens_sum = sum(x for x in range(1, 101) if x % 2 == 0) # 2550
Or List Comprehension:
lst = [x for x in range(1, 101) if x % 2 == 0] # even nums
total = sum(lst) # 2550
I am a beginner too but it looks I can help you some.
for i in range(1, 100):
if(i % 2 == 0):
sum += i
print(sum) // do what you want

Display sum of every number from any specific range with User input

Using below code , i want to display sum for a particular 'n' range lies between two numbers.
start = int(input("Enter the number : "))
end = int(input("Enter the number : "))
i = 1
for i in range(start, end+1):
i+=1
print(i)
Yes, it concatenates two numbers by +1, now to display each number's sum one by one or if i want sum of all numbers from 1 to 100 (Say,1+2+3+4+5+6+7...n) or any range 'n' entered in particular, then how to go. Thanks
One of the Pythonic ways is
from itertools import accumulate
start = int(input("Enter the number : "))
end = int(input("Enter the number : "))
for index, value in enumerate(accumulate(range(start, end+1))):
print(f'Sum from {start} to {index} is : {value}')
Output is the same as from #SuyogShimpi, not really pythonic, more C-style, but maybe easier to understand.
start = int(input("Enter the number : "))
end = int(input("Enter the number : "))
current_sum = 0
for i in range(start, end+1):
current_sum += i
print(f'sum from {start} to {i} is {current_sum}')
you can use Numpy
Installing
pip install numpy
and use numpy.sum
import numpy as np
start = int(input("Enter the number : "))
end = int(input("Enter the number : "))
Sum = np.sum(np.arange(start, end+1))
print(Sum)

Want to print consecutive 1's in

from array import *
n=int(input("Enter the number"))
m=bin(n)
#print(m)
a=array("u",[])
a=int(m[2:])
print(a)
count=0
for i in range(a):
if(a[i]=="1" and a[i+1]=="1"):
count=count+1
print(count)
Here i want to print'ONLY' the number of consecutive 1's that appear in a binary number.
If your logic is correct try this,
n = int(input('Enter a number : '))
nb =bin(n)
l = list(nb)[2:]
count = 0
for i in range(len(l)-1):
if l[i]=='1' and l[i+1]=='1':
count += 1
print(count)

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]))

Using generator to fill integer values in 2-D array

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]]

Resources