is there a faster way to receive input with python? (USACO) - python

I'm new to competitive coding and was doing a practice USACO question with an input structure like this:
5 3
1
6
4
3
1
the first number is the number of numbers below it, and the second number next to it would be needed for something else in the problem
heres the code I wrote to try to recieve the input
a = list(input())
n = int(a[0])
k = int(a[2])
diamonds = []
for x in range(n):
this = int(input())
diamonds.append(this)
the first two numbers I put in a list, converted to int, then assigned them to two variables, I then created an array with a for loop to receive the list of numbers below, converting them to int first
although it works, I feel like this is inefficent and is wasting time, is there another, faster way of doing this?

Related

Python input multiple lines and spaces

Im trying to solve one of the a2oj problems "given three numbers a , b and c. print the total sum of the three numbers added to itself."
I came with this
import sys
numbers = [int(x) for x in sys.stdin.read().split()]
print(numbers[0] + numbers[1] + numbers[2])
I saw many topics but I cant figure out how to read just 3 values from input. I know I can stop this procces by typing CTRL+D, but is there any possibility to make it automatic (after reaching third value)?
Thanks
// Thanks for very quick answers, I made mistake and posted only Problem Statement without Input Format: "three numbers separated by bunch of spaces and/or new lines"
So for example input should look like this:
2
1 4
// Ok thanks to you guys finally I made this:
n = []
while len(n) < 3:
s=input()
i = s.split()
[n.append(int(j)) for j in i]
print(2 * sum(n))
It's working but when I sent my results I got Runtime Error. I have no idea why:
Link: https://a2oj.com/p?ID=346
You could just use:
sys.argv
import sys
numbers = [int(x) for x in sys.argv[1:4]]
print(numbers)
print(sum(numbers))
When inputs are given line by line.
from sys import stdin
sum = 0
for num in stdin.readline(4):
sum = sum + int(num)
print(sum)
When inputs are given on CLI.
from sys import argv
sum = 0
for num in argv[1:4]:
sum = sum + int(num)
print(sum)
Use Python strip() and split() functions as per your usecases
I am not sure what you are looking for, but it seems that you are looking for is the input function, from python's builtins:
x=input()
This reads any input from the user, as a string. You have then to convert it to a number if needed.
You can read three values:
x=input("First value:")
y=input("Second value:")
z=input("Third value:")
As you have now specified more precisely the problem statement, I edit my answer:
In your case, this is not very complicated. I am not going to give you the answer straight away, as it would defeat the point, but the idea is to wrap the input inside a while loop. Something like:
numbers=[]
while (you have less than 3 numbers):
(input one line and add the numbers to your list)
(print the sum of your numbers)
That way you are waiting for as many inputs as you need until you reach 3 numbers. By the way, depending on your input, you might have to check whether you do not get more than 3 numbers.
After seeing the update from the question author and linked the online judge question description, the tweak to his code needed is below. It's worth noting that the expected output is in float and has precision set to 6 and the output is 2 * sum of all inputs, not just sum. There is no description on this in the online judge question and you've to understand from the input vs output.
n = []
while len(n) < 3:
s = input()
i = s.split()
n.extend(float(j) for j in i)
print(format(2 * sum(n), '.6f'))
Screenshot below
But the first version of this answer is still valid to the first version of this question. Keeping them if anyone else is looking for the following scenarios.
To separate inputs by enter aka New lines:
numbers_List = []
for i in range(3):
number = int(input())
numbers_List.append(number)
print("Sum of all numbers: ", sum(numbers_List))
Screenshot:
To separate inputs by space aka Bunch of spaces:
Use map before taking input. I'd suggest using input as well instead of sys.stdin.read() to get input from users, separated by space, and ended by pressing Enter key.
Very easy implementation below for any number of inputs and to add using sum function on a list:
numbers = list(map(int, input("Numbers: ").split()))
print("Sum of all numbers: ", sum(numbers))
The screenshot below and link to the program is here
Read Python's Built-in Functions documentation to know more about all the functions I used above.

Wrong Answer python3.6

You are given a set S and Q queries. Initially, S is empty. In each query:
You are given a positive integer X.
You should insert X into S.
For each y∈S before this query such that y≠X, you should also insert y⊕X into S (⊕ denotes the XOR operation).
Then, you should find two values E and O: the number of elements of S with an even number of 1's and with an odd number of 1's in the binary representation, respectively.
I have tried splitting the problem into smaller subproblems but it seems to exceed time because of large input size and large list size. Any suggestion into the code and further optimization will be very helpful.I have mow used set but the expected output is not as same as my output. Any suggestions as where I am going wrong in the solution code..?
s=set()
def fun(n,q):
c=0
cc=0
s.add(n)
for k in range(len(list(s))):
if list(s)[k]!=n:
s.add((list(s)[k])^n)
for k in s:
if bin(k)[2::].count('1')%2==0:
c+=1
else:
cc+=1
print(c,cc)
for _ in range(int(input())):
q=int(input())
for j in range(q):
n=int(input())
fun(n,q)
Example Input:
1
3
4
2
7
Example Output:
0 1
1 2
3 4
The first thing i see wrong on your code is that S should be a set of numbers. A list can have duplicates, so you need to work with sets
And to optimize your script, you can start by improving how you count the amount of enabled bits in your number expressed in binary. Such count is called the hamming weight of a string.
Search it on the web. For instance you have this article
I think you are inserting duplicate value in your List. fix it you will be good to go.
Solution And Reference :- https://whitefox-89ea6.firebaseapp.com/

Dice game (simulating many throws with 3 dices)

I am trying to code a dice game:
How do I write a function that is supposed to simulate 1000 throws of 3 dice and print the number of times a throw resulted in exactly 2 of the dice, but not all 3, landing on the same number. Meaning not (1,2,3) or (5,5,5), but like this (1,2,2).
def throw():
I know I need to use the random- library to generate numbers between 1 and 6.
What I need is example code on how I can approach this and what to do.
Use a for loop and list comprehension to generate the throw:
for i in range(1000):
throw = [random.randint(1, 6) for x in range(3)]
Then just write code to check your condition, something like:
valid = any([throw.count(i) == 2 for i in range(1, 6)])
Then if it's valid is True you can do with it what you need.
The function could be something like this:
import random
matches = 0
for i in range(1000): # 1000 throws
result = (random.randint(1,6), random.randint(1,6), random.randint(1,6)) # three dices randomly from 1 to 6 in a tuple (list)
for i in range(1,7): # count from 1 to 6
if result.count(i) == 2:
matches += 1
break # breaking out of this for-loop for performance improvement
print("Got "+str(matches)+" matches.")
Of course, this code could be heavily improved. But according to your question I assume that you are quite new to Python programming. This is why I tried to write a code that is self-explanatory.
Meta: please keep in mind that Stack Overflow is not the right place to ask for specific coding. It's intended to be a place where you provide code which contains error that you are unable to fix.

I have to write a program that calculates and displays the total score using a for loop?

I'm quite new to the for loops in Python. So, I want to write a program that asks the user to enter to enter 20 different scores and then I want the program to calculate the total and display it on the screen. How could I use a for loop to do this?
edit: I can ask the user to for the different numbers but I don't know how to then add them.
Without giving you the full code here is the pseudocode for what your code should look like
x = ask user for input
loop up till x //Or you could hard code 20 instead of x
add user input to a list
end
total = sum values in list
print total
Here are all the things you need to implement the logic
User input/output:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html
Loops:
https://wiki.python.org/moin/ForLoop
Summing a list:
https://docs.python.org/2/library/functions.html
Try something like this:
total = 0; # create the variable
for i in range(1,20): # iterate over values 1 to 20 as a list
total += int(input('Please enter number {0}: '.format(i)));
print("Sum of the numbers is '{0}'".format(total))
I'd suggest you go through the tutorials on the python site:
Python 3 is here https://docs.python.org/3/tutorial/index.html
Python 2 is here https://docs.python.org/2/tutorial/index.html
I could go into a lot of detail here and explain everything, however I'd only be duplicating the resources already available. Written far better than I could write them. It would be far more beneficial for you (and anyone else reading this who has a similar issue) to go through these tutorials and get familiar with the python documentation. These will give you a good foundation in the basics, and show you what the language is capable of.
Input
To read a value from the commandline you can use the input function, e.g. valueString = input("prompt text"). Notice the value stored is of type string, which is effectively an array of ASCI/Unicode characters.
So in order to perform math on the input, you first need to convert it to its numerical value - number = int(valueString) does this. So you can now add numbers together.
Adding numbers
Say you had two numbers, num1 and num2, you can just use the addition operator. For example num3 = num1 + num2. Now suppose you have a for loop and want to add a new number each time the loop executes, you can use the total += newNum operator.
total = 0
for _ in range(1,20):
num = input('> ')
total += int(num)
print(total)
I hope this helps.

python elements in line without raw_input()

I have an input stream of numbers
1 2 3 4 5 6 7 8 9 10 11 12 and it goes on......
now in python, we have to take input by raw_input() and then map(int,raw_input.split()) and then do whatever processing one has to do.
for eg.
n = map(int,raw_input().split())
for i in n:
print i%2==0
So in the above code, i have first taken all inputs, converted them to integer and ran a loop to check if each integer is even number or not.
I can do the same thing in Java, but now i can simply give result just as soon as I get input.
for eg. Assuming number of inputs ( n ) is given, the following program, takes input from the above given input feed and keep on giving requisite output.
for(i = 0 ; i < n ; i++ ){
n = in.nextInt();
System.out.println(n%2==0);
}
I want to know, if there is some method in python by which we can take n inputs from a line and keep processing it in continuation.
And how are the two above programs differ performance wise.
I think you want something like this (assumes n is already set)
in = raw_input().split()
for i in range(n):
i = int(in[i])
print(i%0 == 0)
This is analogous to the Java code, but like the Java code, this will raise an error if there are fewer than n numbers, or if any of the items in the input are not integers.

Categories