Taking user input of 2-D array in a given format - python

I have a 2-D 6x6 array, A.
I want its values to be input by the user in the following format or example:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
where the 0's indicate the places where the user would write their values.
This is my code. It returns an error in split().
def arr_input(x):
for i in range(6):
for j in range(6):
n = int(input().split(' '))
if n>=-9 and n<=9:
x[i][j] = n
print "\n"
I don't want input in a single line. Please help!
EDIT 1
The code I needed was already provided :D. Nevertheless, I learned something new and helpful. Here is the existing code to do the task I wanted:
arr = []
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)

First of all, you are using input() which returns int when you enter numbers in terminal. You should use raw_input() and get it line by line.
Second, you are trying to convert a list to integer, you should loop through the list values, convert and insert on the resulting list.
Fixed code:
def arr_input(x):
for i in range(6):
num_list = raw_input().split(' ')
for j, str_num in enumerate(num_list):
n = int(str_num)
if n >= -9 and n <= 9:
x[i][j] = n
print "\n"
Here, I used enumerate() to loop though the number list by getting its index each iteration.

There's an inconsistency in how you're treating the input. In python 2.7, the input() function is designed to read one, and only one, argument from stdin.
I'm not exactly sure which way you're trying to read the input in. The nested for loop suggests that you're trying to read the values in one by one, but the split suggests that you're doing it line by line. To cover all bases, I'll explain both cases. At least one of them will be relevant.
Case 1:
Let's say you've been inputting the values one by one, i.e.
1
4
9
4
...
In this case, what's happening is that the input() function is automatically parsing the inputs as integers, and when you try running split() on an integer there's a type error. Python is expecting a string and you're providing an int. That's going to break. There's an easy solution--this can be fixed by simply replacing that line with
n = input()
Case 2: Let's say you're inputing the numbers line by line, as strings. By this, I mean something like:
"1 3 4 5 7 9"
"4 1 8 2 5 1"
...
What's occurring here is that int(...) is trying to cast a list of strings into an integer. That will clearly break the code. A possible solution would be to restructure the code by gett rid of the inner for loop. Something like this should work:
def arr_input(arr):
for i in range(6):
s = input()
nums_s = s.split(' ')
nums = [int(x) for x in nums_s]
arr.append(nums)
print "\n"
return arr
# Usage
a = []
print(a)
a = arr_input(a)
print(a)

Give this one-liner a try:
def arr_input(N=6):
print 'Enter %d by %d array, one row per line (elements separated by blanks)' % (N, N)
return [[n if abs(n)<=9 else 0 for n in map(int, raw_input().split())] for i in range(N)]
The following interactive session demonstrates its usage:
>>> A = arr_input(3)
Enter 3 by 3 array, one row per line (elements separated by blanks)
1 2 -3
4 5 -6
8 9 10
>>> A
[[1, 2, -3], [4, 5, -6], [8, 9, 0]]

Related

Why is it giving runtime error on codeforces for python?

So I am very new to code and have learnt the basics of python. I am testing out my skills on codeforces by first solving some of their easier problems. I am trying to do 158A on codeforces. I think I have got it because it passed a few tests I assigned. So, I tried submitting it and it told me something about a runtime error. I don't really know what it is so I would like it if someone could tell me what it is and how to fix it in my code. Here is the link to the problem: https://codeforces.com/problemset/problem/158/A
n = int(input())
k = int(input())
b = []
for i in range(n):
a = int(input())
b.append(a)
c = 0
for i in b:
if i >= b[k]:
c = c+1
else:
pass
print(c)
The input you are given is "8 5" and "10 9 8 7 7 7 5 5". That doesn't mean you are given "8" and "5" as two different inputs. It means you have a very long string that contains numbers separated by spaces. You should turn these into a list.
a = input()
n = int(a.split(" ")[0])
k = int(a.split(" ")[1])
a should equal "8 5". We then turn the string into a list using a.split(" "). This will produce ["8", "5"].
In the problem 158A the expected input are:
1. Two numbers (int) separated by a single space, where 1 ≤ k ≤ n ≤ 50
2. n space-separated integers, where ai ≥ ai + 1
There is also a condition: Scores MUST be positive (score>0) so you can advance
This is all you need, I tested it and I got the expected output everytime
a = input("Input n and k: ")
n = int(a.split(" ")[0])
k = int(a.split(" ")[1])
b = input("Input n scores: ")
willAdvance = 0
scores = b.split()
print(scores)
for element in scores:
if int(element) >= int(scores[k-1]) and int(scores[k-1]) > 0:
willAdvance += 1
print(willAdvance)
TEST
Input:
8 5
10 9 8 7 7 7 5 5
Output:
6
Input:
4 6
0 0 0 0
Output:
0

Formatting unknown output in a table in Python

Help! I'm a Python beginner given the assignment of displaying the Collatz Sequence from a user-inputted integer, and displaying the contents in columns and rows. As you may know, the results could be 10 numbers, 30, or 100. I'm supposed to use '\t'. I've tried many variations, but at best, only get a single column. e.g.
def sequence(number):
if number % 2 == 0:
return number // 2
else:
result = number * 3 + 1
return result
n = int(input('Enter any positive integer to see Collatz Sequence:\n'))
while sequence != 1:
n = sequence(int(n))
print('%s\t' % n)
if n == 1:
print('\nThank you! The number 1 is the end of the Collatz Sequence')
break
Which yields a single vertical column, rather than the results being displayed horizontally. Ideally, I'd like to display 10 results left to right, and then go to another line. Thanks for any ideas!
Something like this maybe:
def get_collatz(n):
return [n // 2, n * 3 + 1][n % 2]
while True:
user_input = input("Enter a positive integer: ")
try:
n = int(user_input)
assert n > 1
except (ValueError, AssertionError):
continue
else:
break
sequence = [n]
while True:
last_item = sequence[-1]
if last_item == 1:
break
sequence.append(get_collatz(last_item))
print(*sequence, sep="\t")
Output:
Enter a positive integer: 12
12 6 3 10 5 16 8 4 2 1
>>>
EDIT Trying to keep it similar to your code:
I would change your sequence function to something like this:
def get_collatz(n):
if n % 2 == 0:
return n // 2
return n * 3 + 1
I called it get_collatz because I think that is more descriptive than sequence, it's still not a great name though - if you wanted to be super explicit maybe get_collatz_at_n or something.
Notice, I took the else branch out entirely, since it's not required. If n % 2 == 0, then we return from the function, so either you return in the body of the if or you return one line below - no else necessary.
For the rest, maybe:
last_number = int(input("Enter a positive integer: "))
while last_number != 1:
print(last_number, end="\t")
last_number = get_collatz(last_number)
In Python, print has an optional keyword parameter named end, which by default is \n. It signifies which character should be printed at the very end of a print-statement. By simply changing it to \t, you can print all elements of the sequence on one line, separated by tabs (since each number in the sequence invokes a separate print-statement).
With this approach, however, you'll have to make sure to print the trailing 1 after the while loop has ended, since the loop will terminate as soon as last_number becomes 1, which means the loop won't have a chance to print it.
Another way of printing the sequence (with separating tabs), would be to store the sequence in a list, and then use str.join to create a string out of the list, where each element is separated by some string or character. Of course this requires that all elements in the list are strings to begin with - in this case I'm using map to convert the integers to strings:
result = "\t".join(map(str, [12, 6, 3, 10, 5, 16, 8, 4, 2, 1]))
print(result)
Output:
12 6 3 10 5 16 8 4 2 1
>>>

Adding unique integers

Write a Python program that reads an integer that gives the number of integers to be read and then reads these integers, one per line, into a list. Print the total of these integers except that if an integer appears more than once it will not be counted.
You may not use the count method of lists. For example, the input:
• 5 1 2 3 4 5 would give 15;
• 5 1 2 3 4 2 would give 8;
• 5 1 2 1 4 2 would give 4; and
• 5 2 2 2 2 2 would give 0.
My code works but is a little hard to read, anyways to so simply this without imports?
xs = [int(input()) for i in range(int(input()))]
print(sum([xs[i] for i in range(len(xs)) \ if xs[i] not in xs[:i] + xs[i + 1:]]))
Split the counting and summing steps. Do one pass over the list to determine the unique elements, then another to sum them.
from collections import Counter
def sum_unique(inputs):
counts = Counter(inputs)
return sum(num for num, count in counts.items() if count == 1)
xs = [int(input()) for i in range(int(input()))]
print(sum_unique(xs))
Edit: Sorry, I didn't see "without imports". You can make a regular dict act like a Counter, it's just not as pretty.
def sum_unique(inputs):
counts = {}
for x in inputs:
counts[x] = counts.get(x, 0) + 1
return sum(num for num, count in counts.items() if count == 1)

Taking an input of any length of number and splitting them one character each

I'm a few weeks into learning python and I am trying to write a script that takes an input of any length of numbers and splits them in one-character lengths. like this:
input:
123456
output:
1 2 3 4 5 6
I need to do this without using strings, and preferably using divmod...
something like this:
s = int(input("enter numbers you want to split:"))
while s > 0:
s, remainder = divmod(s, 10)
I'm not sure how to get the spacing right.
Thank you for the help.
As your priority is to use divmod, you can do it like this:
lst=[]
while s>0:
s, remainder = divmod(s, 10)
lst.append(remainder)
for i in reversed(lst):
print i,
Output:
enter numbers you want to split:123456
1 2 3 4 5 6
You can use join() to achieve that. Cast to string if your are using python 2.*
s = input("enter numbers you want to split:")
s= str(s)
digitlist=list(s)
print " ".join(digitlist)
In case, you are in need of integers, just do it.
intDigitlist=map(int,digitlist)
What about the following using the remainder:
s = 123456
output = []
while s > 0:
s, r = divmod(s, 10)
output.append(r)
fmt='{:<12d}'*len(output)
print fmt.format(*output[::-1])
Output:
1 2 3 4 5 6
This also uses some other useful Python stuff: the list of digits can be reversed (output[::-1]) and formatted into 12-character fields, with the digit aligned on the left ({:<12d}).
Try it with mod:
while x > 0:
x = input
y = x % 10
//add y to list of numbers
x = (int) x / 10
e.g. if x is 123:
123 % 10 is 3 -> you save 3.
the Integer value of 123 / 10 is 12.
Then 12 % 10 is 2 -> you save 2
Int of 12 / 10 is 1.
1 % 10 = 1 -> you save 1
Now you have all numbers. You can invert the list after that to have it like you want.
You can iterate over Python string amd use String.join() to get result:
>>>' '.join(str(input("Enter numbers you want to split: ")))
Enter numbers you want to split: 12345
1 2 3 4 5

How do I print out the sum of a list given certain constraints

I'm trying to print the sum of a list generated through raw_input.
The numbers in the list must be between 1 and 1000, inclusive. The length of the list must be below 1000.
here is my code thus far:
initial_list = raw_input()
integer= initial_list.split(' ')
if len(integer) <= 1000:
for i in integer:
if i >= 1 and i<=1000:
actual_integer = map( int, integer)
print sum(actual_integer)
This does not print anything. Any suggestions and/or alternatives?
If I understand your objective correctly, you've got all the right ideas, you just need to re-order your logic a little and make sure you are clear in your head about when you're dealing with a list of values and when you're dealing with a single value.
You may wish to consider your variable naming, too, as good names can help you keep track of whether the variable has a type with multiple values or single values. I've updated your code with that in mind
initial_list = raw_input().split() # split(' ') works, but you don't actually need the ' ',
# split() on its own does the same job here
if len(initial_list) <= 1000:
actual_integers = map(int, initial_list) #Moved to here. Note that
#actual_integers is a list
#so for the following comparison
#you just want to look at the max
#and min (individual values)
if min(actual_integers) >= 1 and max(actual_integers) <= 1000:
print sum(actual_integers)
else: #Just added two nice messages to the user if it doesn't print out.
print 'integers must be in range 1-1000 inclusive'
else:
print 'your list must have 1000 integers or fewer'
This code here does what you need but there is no error checking.
initial_list = raw_input() # there should be some prompt text
# no error checking
integer = initial_list.split(' ')
# no output for lists > 1000
if len(integer) <= 1000:
print sum(filter(lambda i: 0 < i <= 1000, map(int, integer)))
The output
$ python test.py
1 2 3 1500 0
6
If I understand your question correctly, this maybe what you're looking for.
This code will prompt the input and append the input to the list lst until lst will have 1000 elements. It will only take an input if the input is a number between 1 and 1000 and it will give you the sum after every input.
lst = []
while len(lst) <= 999:
initial_list = raw_input('Input numbers between 1 and 1000:')
if initial_list.isdigit() and int(initial_list) <= 1000 and int(initial_list) >= 1:
lst.append(int(initial_list))
print 'List:', lst #prints the list
total = sum(lst)
print 'List Sum:', total #prints the list sum
else:
print 'Input must be numbers between 1 and 1000'
Output:
Input numbers between 1 and 1000:12
List: [12]
List Sum: 12
Input numbers between 1 and 1000:45
List: [12, 45]
List Sum: 57
Input numbers between 1 and 1000:156
List: [12, 45, 156]
List Sum: 213
Input numbers between 1 and 1000:256
List: [12, 45, 156, 256]
List Sum: 469
Input numbers between 1 and 1000:

Categories

Resources