How to take multiple integer inputs given in multiple lines? - python-3.x

Is it possible to take multiple newline integer inputs.
For example:
2
1 44 2 14
2 42 8 23
In the first line, it is given that there will be 2 lines of input.Then I need to take the each line in separate array.
I need to take the inputs from command line not from a file

numlines = int(input().strip())
for lineno in range(numlines):
line = input().split()
print(line)

First take the first line that indicates how many more lines will be, and then save each line as a list of ints inside a list. You don't want to dynamically create lists (as new names) for each line, simply pack them in one big list:
num_of_lines = int(input())
lines = []
for _ in range(num_of_lines):
lines.append(list(map(int, input().split())))
print(lines)
for line in lines:
print(line)
And on your example input this prints:
[[1, 44, 2, 14], [2, 42, 8, 23]]
[1, 44, 2, 14]
[2, 42, 8, 23]

lines = ""
for i in xrange(5):
lines+=input()+"\n"
print (lines)
Or
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
print (lines)
text = '\n'.join(lines)

Related

Convert list to a particular format [(123, 123), (345,875)..]

I have the following list:
l = [12, 23,54, 67, 87,98,15, 90, 44,81]
I would like to convert them into pairs with parenthesis. Desired output should look like the following:
[(12, 23),(54, 67), (87,98),(15, 90), (44,81)]
What I tried so far?
print('{}'.format(' '.join('({},)'.format(i) for i in l)))
This does not print the list as pairs. How do I solve this?
l = [12, 23,54, 67, 87,98,15, 90, 44,81]
my=[]
for i in range(0,len(l),2):
my.append(tuple(l[i:i+2]))
print(my)
Rather than for i in l, you'd need to use a range to allow you to set an increment by which to step through. range takes 3 arguments - a starting number, an end number, and (optionally; it defaults to 1) an increment.
Something like this:
tuple_list = [(l[i], l[i+1]) for i in range(0, len(l), 2)]

How to take two inputs in one line separated by space in python

So I am practicing in hacker earth and I have to take two inputs in a single line separated by space.
The below code is what I used:
x, y = [x for x in input("Enter two value: ").split()]
It is supposed to take input that looks like '2 5'
And it is returning an error:
Execution failed
ValueError : not enough values to unpack (expected 2, got 1)
Stack Trace:
Traceback (most recent call last):
File "/tmp/165461120/user_code.py", line 13, in
x, y = [x for x in input("Enter two value: ").split()]
ValueError: not enough values to unpack (expected 2, got 1)
What I think I understood is that it is giving two values as a single string. If so how do I take separate them and convert them into integers?
To take two inputs
x, y = input("Enter two value: ").split()
This should do the trick. To convert to int you can do it seprately on the both x and y.
Or better way is to use a map function
x, y = map(int, input().split())
For your case, only typecasting is remaining, so that splitted numbers becomes int. So, just you have to add
x, y = [int(x) for x in input("Enter two value: ").split()]
Alternatively, For taking 2 inputs in single line, you can use map also
x, y = map(int, input().split())
This is happening because Hacker Earth, in almost all cases, gives its input line by line.
In almost all cases, the inputs are of the form below.
1
2 3 4
5
6 7 8
This will differ on problem by problem basis and needs to be personalized for each problem.
You are getting the error not enough values to unpack because Hacker Earth is giving only a single input, and you are expecting 2. If it had been more than 2, then the error would have been too many values to unpack.
In all probability its because you are trying to input the number of test cases, which is the first input, and a single number input, in most hacker earth problems.
Process-01 : using list comprehension
whole_line = input() # 1 2 3 4 5
strings = whole_line.split(' ') # ['1', '2', '3', '4', '5']
# remove extra space within numbers if any from list
numbers = [int(num) for num in strings if len(num)>0] # [1, 2, 3, 4, 5]
print(numbers) # [1, 2, 3, 4, 5]
Now you can write down the whole logic within one line like below
numbers = [ int(num) for num in input().split(' ') if len(num)>0 ]
print(numbers)
Process-02 : using filter and map function
whole_line = input() # 1 2 3 4 5
strings = whole_line.split(' ') # ['1', '2', '3', '4', '5']
# remove extra space within numbers if any from list
strings = list(filter(lambda x :len(x)>0 ,strings))
numbers = list(map(int,strings)) # convert each string to int
print(numbers) # [1, 2, 3, 4, 5]
Now you can write down the whole logic within one line like below
numbers = list(map(int,filter(lambda x : len(x)>0,input().split(' '))))
print(numbers)
In [20]: a,b = raw_input().split()
12 12.2
In [21]: a = int(a)
Out[21]: 12
In [22]: b = float(b)
Out[22]: 12.2
You can't do this in a one-liner (or at least not without some super duper extra hackz0r skills -- or semicolons), but python is not made for one-liners.

python random lottery number generator game

I have to make a game where like the lottery my program generates 5 random numbers from a list of numbers 1-50 and one additional number from a list of numbers 1-20 and combines them into a final list that reads eg: (20, 26, 49, 01, 11, + 06) where two numbers are never repeated like (22, 11, 34, 44, 01, + 22) <--- this is what I don't want
attached below is the code I have written yet how do I make it so two numbers or more are never repeated and to add the + into my list without the "" signs
input:
import random
a = list(range(1,51))
b = random.randint(1, 20)
temp = []
for i in range(5):
random.shuffle(a)
temp.append(random.choice(a[:5]))
temp.append('+')
temp.append(b)
print(temp)
output:
[14, 12, 3, 16, 23, '+', 9]
You can not add + without the ' around them - they mark the + as string.
Also: you shuffle your list - simply take the first 5 values - they are random and your list does not contain any dupes so you are golden:
nums = list(range(1,51))
random.shuffle(nums)
five_nums = nums[:5]
print(five_nums) # [44, 23, 34, 38, 3]
To simplyfy it, use:
import random
# creates 5 unique elements from 1..50 and adds a + and a [0-19]+1 number
randlist = random.sample(range(1,51),k=5) + ["+", random.choice(range(20))+1]
print(randlist)
Now you got mixed numbers and strings - you can create a combined string by:
print("You drew {} {} {} {} {} {} {}".format(*randlist))
To create a string like
[48, 2, 9, 6, 41, '+', 8]
You drew 48 2 9 6 41 + 8
Doku:
random.sample (draw without putting back)
You can try the following:
import random
randList, run = [], 0
while run < 6:
number = random.randint(1,51)
if number not in randList:
if run == 5:
randList.append('+'+str(number))
break
randList.append(number)
run += 1
print(randList)
You can't have a string in a list without quotes, however, if you were to print every item in the list (using a for loop or join), the quotes wouldn't be there.
This code will generate a list of 7 random numbers
import random
def main():
numbers = []
for num in range(7):
num = random.randrange(50)
numbers.append(num)
print(numbers)
main()
#No repeating numbers and sorted output
import random
picks = int (input("How Many Picks ?: "))
for i in range (picks):
num_list = random.sample(range(1, 45), 5,)
num_list.sort()
joker_num = random.sample(range(1, 20), 1)
print("Lucky Numbers :", num_list, "-", "Joker :", joker_num)
It didn't work because you need to have
import random

Python: Use a for loop to get Nth number out of a list

I need to get every 3rd value out of a list and add it to a new list.
This is what I have so far.
def make_reduced_samples(original_samples, skip):
skipped_list = []
for count in range(0, len(original_samples), skip):
skipped_list.append(count)
return skipped_list
skip is equal to 3
I get the indexes and not the value of the numbers in the list.
It gives me [0,3,6]. Which are the indexes in the list and not the value of the indexes.
The example I am given is:
In this list [12,87,234,34,98,11,9,72], you should get [12,34,9].
I cannot use skipped_list = original_samples[::3] in any way.
You need to append the value of the original_samples array at the index. Not the index (count) itself.
def make_reduced_samples(original_samples, skip):
skipped_list = []
for count in range(0, len(original_samples), skip):
skipped_list.append(original_samples[count])
return skipped_list
The correct, most pythonic, and most efficient way to do that is to use slicing.
lst = [12, 87, 234, 34, 98, 11, 9, 72]
skipped_list = lst[::3]
print(skipped_list) # [12, 34, 9]
If the step does not obey a linear relation (which it does here), then you could use a list-comprehension with enumerate to filter on the index.
skipped_list = [x for i, x in enumerate(lst) if i % 3 == 0]
print(skipped_list) # [12, 34, 9]
One liner:
skipped_list = [j for (i,j) in enumerate(original_samples, start=1) if i % 3 == 0]

How to insert a String as Integer to a List in Python

I need to insert a number (user input) as an integer to a Python list.
My code:
count = 0
list1 = []
for number in input():
if number != ' ':
list1.append(int(number))
Input: 10 11 12
Output: [1, 0, 1, 1, 1, 2]
Expected Output: [10, 11, 12]
Looping over a string (such as the one returned by input()) will loop over the individual characters in the string:
>>> s = 'hi guys'
>>> for char in s:
... print(char)
...
h
i
g
u
y
s
>>>
To loop over the "words" (i.e. substrings separated by spaces), you want to split() the user's input instead:
>>> s = 'hi guys'
>>> words = s.split()
>>> words
['hi', 'guys']
>>> for word in words:
... print(word)
...
hi
guys
>>>
So in your case, that would be:
for number in input().split():
list1.append(int(number))
We can leave the if number != ' ': out because split() already gets rid of all the spaces and simply returns a list of the numbers.
Here You Go
input_array = []
c_input = input('please enter the input\n')
for item in c_input.split():
input_array.append(int(item))
print (input_array)
input: - 1 11 23 23 456
Output:- [1, 11, 23, 23, 456]
i hope you find it useful
You should use split method to split the values as a list with string:
str_nums = input.split() #will give ['10','11','12']
then
lst_nums = []
for i in str_nums.split():
lst_nums.append(int(i))
print(lst_nums)
#output [10,11,12]
You can also use map and split together.
inp = "10 11 12"
print(list(map(int,inp.split(" "))))
#Output
[10,11,12]
Or
print([int(i) for i in input().split()])

Resources