Python STDIN for multiple values - python

Hello I am having trouble inputting two numbers from stdin using the following code as I am not quite yet familiar with this feature, when I input numbers manually the code seems to work properly but I can't get sys.stdin.readline to properly work.
import sys
def k(upto):
def collatz(n):
if n < upto and lst[n] > 0:
return lst[n]
if n % 2 == 0:
val = collatz(n/2) + 1
else:
val = collatz((3*n + 1)/2) + 2
if n < upto:
lst[n] = val
return val
lst = [0]*upto
lst[1] = 1
lst[0] = 1
for i in range(mini,upto):
collatz(i)
return max(lst)
line=int(sys.stdin.readline())
maxi = max(line)
mini = min(line)
print k(maxi)
The code produces the following error: TypeError: 'int' object is not iterable. Any assistance would be appreciated.
EDIT ::: Should have mentioned only two numbers will be input, one per line.

After reading your comment, it looks like you want something like this
line = list()
for x in range(2):
line.append(int(sys.stdin.readline()))
That will read 2 lines from STDIN, convert each line to an int, and append each value to line.

The "one per line" is an important information :)
If you're reading one per line you're code is quite close - except you're reading only one line: your variable line is only one number - hence min and max can't work.
You could do something like
i1 = int(raw_input("Enter first number: "))
i2 = int(raw_input("Enter second number: "))
maxi = max(i1, i2)
mini = min(i1, i2)
...
note: If you switch to Python 3 (recommended) it's input() instead of raw_input()
old version:
What is the input? A list of integers, e.g. 2 3 5? This will be interpreted as a string "2 3 5". To convert this into integers you to have to do something like
line = [int(i) for i in sys.stdin.readline().split()]
This
- will split() the input into an array of strings ["2", "3", "5"] and then
- apply the int() conversion to each element of the array.

Related

input expected at most 1 argument, got 2 python

I keep receiving this error (TypeError: input expected at most 1 argument, got 2) and I can't figure out why. The goal of the code is to keep asking for a number until that number is between one and a variable called n.
def enterValidNumber(n):
while True:
num = int(input("Input a number from 1 to", n))
if num >= 1 and num <= n:
break
enterValidNumber(17)
Yes, you are right; you are giving two parameters to input. To put n into the prompt string, you can use an f-string:
num = int(input(f"Input a number from 1 to {n}"))
You can always go with j1-lee's answer but I would have another suggestion:
num = int(input("Input a number from 1 to " + str(n)))
this would work well too!

Generating a palindrome number taken from input

I'm writing a program that takes a number from input and generates it's palindrome number. My program only prints the first half not the second. I tried reverse, didnt work.I have incluede those lines as comment.
My Code:
def show_palindrome(maximum):
maximum = int(input("Enter Number : "))
for number in range(1, maximum + 1):
temporary = number
reverse = 0
while (temporary > 0):
reminder = temporary % 10
reverse = (reverse * 10) + reminder
temporary = temporary //10
if(number == reverse):
#number2 = number[::-1]
#print(number,number2, end = '')
print(number, end = '')
show_palindrome(3)
My output:
123
The output I need:
12321
I believe you're looking for something like this:
def show_palindrome(maximum = None):
if not maximum:
maximum = input("Enter Number : ")
output = str(maximum)
for number in range(1, int(maximum)):
output = str(int(maximum) - number) + str(output) + str(int(maximum) - number)
return output
print(show_palindrome(3))
this returns 12321 for instance
A couple of things I would do differently in your function:
If you're going to require the input in the def (The way you make it optional is to set it equal to something when you declare it like I have it set to None (maximum=None), then you don't need the input() statement.
Since you already know how long you want it to be ( you require it declared when you initialize the function, it's just 2*maximum - 1) there's really no need to use a while loop.
Other than that good job! Keep it up!
You can try something simpler like this:
def show_palindrome():
num = input("Enter Number : ")
print(num + num[:-1][::-1])
show_palindrome()
Input:
123
12
1
Output:
12321
121
1
Apart from the string slice method (as used by #PApostol), you could also use the reversed method :
def show_palindrome():
value = input("Enter Number : ")
print(value[:-1] + "".join(reversed(value)))
Input:
123
Output:
12321
def palindrome(maximum):
number = ''.join([str(num) for num in range(1, maximum + 1)])
return int(number + number[-2::-1])
print(palindrome(3))
Output:
12321
Your code seems over complicated, and I don't even know what to fix in it. What I can tell is that passing a parameter maximum to overwrite it just after with maximum = int(input("Enter Number : ")) is useless, don't pass the parameter.
So let's back to easy things
Build palindrome using strings method : slicing backwards from index -2, and reverse it with -1 increment
def show_palindrome():
value = input("Enter Number : ")
print(value + value[-2::-1])
Build palindrome using math operations : save the remainder, except the first one
def show_palindrome():
value = input("Enter Number : ")
result = value
value = int(value) // 10 # remove last char which would be redundant
while value > 0:
result += str(value % 10)
value = value // 10
print(result)
show_palindrome()

How to break a while loop when input is a particular string?

I need to stop adding up user inputs when one of them is the string "F".
So basically If my input is a int then : += result, if the same input variable is a string then I need to stop and add them together.
My code actually works and has the same inputs and outputs the exercise demands but I'm very unhappy with the way I resolve it.
This is my code:
import numbers
cat = int(input())
def norm(cat):
res = 0
for n in range(cat):
x = int(input())
res += x
print(res)
def lon():
res = 0
while 2 > 1:
try :
y = int(input())
if isinstance(y,int):
res +=y
except:
print(res)
break
if cat >= 0 :
norm(cat)
else:
lon()
It's actually breaking the while loop in a stupid way by checking if my variable is an int. (I need to make it stop by simply pressing F)
Is there any cleaner and shorter way to obtain the same outputs?
Example of the actual inputs-outputs I expect :
in: out:16 (1 + 3 + 5 + 7)
4
1
3
5
7
in: out:37 (1 + 3 + 5 + 7 + 21)
-1
1
3
5
7
21
F
You could have written it a bit shorter:
result = 0
while True:
line = input()
try:
result += int(line)
except ValueError:
break
print(result)
Notice:
import numbers isn't needed. (I didn't even know that existed!)
Instead of 2 > 1, you can use True.
You don't need to check isinstance(..., int) since int() enforces that.
This runs until any non-integer string is reached.
If you want to specifically check for "F" only, it's a bit easier:
result = 0
while True:
line = input()
if line == "F":
break
result += int(line)
print(result)
Note that without using try, you'll crash the program if you input a non-integer, non-"F" string.

Python == Function to Count All Integers Below Defined Variable, Inclusive [duplicate]

This question already has answers here:
Python Memory Error while iterating to a big range
(3 answers)
Closed 6 years ago.
Sorry I have to ask such a simple question, but I've been trying to do this for a while with no luck, despite searching around.
I'm trying to define a function that will get user input for X, and then add every integer from 0 to X, and display the output.
For example, if the user inputs 5, the result should be the sum of 1 + 2 + 3 + 4 + 5.
I can't figure out how to prompt the user for the variable, and then pass this variable into the argument of the function. Thanks for your help.
def InclusiveRange(end):
end = int(input("Enter Variable: ")
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
Just delete argument "end" from function header and use your function.
InclusiveRange()
or define code in other way:
def InclusiveRange(end):
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
end = int(input("Enter Variable: ")
InclusiveRange(end)
Here's an itertools version:
>>> from itertools import count, islice
>>> def sum_to_n(n):
... return sum(islice(count(), 0, n + 1))
>>>
>>> sum_to_n(int(input('input integer: ')))
input integer: 5
15
You should take the user input out of the function, and instead call the function once you have received the user input.
You also need to store the sum in a separate variable to start, otherwise you're only adding 1 each iteration. (I renamed it to index in this example as it reflects it's purpose more).
def InclusiveRange(end):
index = 0
sum = 0
while index <= end:
sum += start
index += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, sum))
end = int(input("Enter Variable: "))
InclusiveRange(end)
Demo
Instead of using a loop, use a range object, which you can easily send to sum(). Also, you're never actually using the passed end variable, immediately throwing it away and binding end to a new value. Pass it in from outside the function.
def inclusive_range(end):
num = sum(range(end+1))
print("The total of the numbers, from 0 to {}, is: {}".format(end, num))
inclusive_range(int(input("Enter Variable: ")))
You can also use a math formula to calculate the sum of all natural numbers from 1 to N.
def InclusiveRange(end):
''' Returns the sum of all natural numbers from 1 to end. '''
assert end >= 1
return end * (end + 1) / 2
end = int(input("Enter N: "))
print(InclusiveRange(end))

Python list numbers with selection

I'm new to programming and currently learning python with reference book Python Programming Fundamentals. Here is one of the question I am dealing with:
1: Request user to input a list of numbers.
2: Then output those numbers which is in between 0 and 100.
Following is my code:
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = s.split() # Now lst is a list of strings.
output = [] # Here is the beginning of the accumulator pattern
for e in lst:
if float(e) > 0 and float(e) < 100 : # inbetween 0 and 100
output = output.append(float(e))
else:
output = output
print("The number between 0 and 100 are ", output)
And the error is:
File "c:\Users\HKGGAIT001\Desktop\1.py", line 7, in <module>
output = output.append(float(e))
builtins.AttributeError: 'NoneType' object has no attribute 'append
Supposing you are using Python3 (because it's unlikely the .split() would be successful in Python2)
This part is ok
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = s.split() # Now lst is a list of strings.
output = [] # Here is the beginning of the accumulator pattern
You can write the loop like this
for e in lst:
if 0 < float(e) < 100 : # inbetween 0 and 100
output.append(float(e))
Notice that there are two comparisons. There is an implicit and. This is called a chained comparison
This pattern can be reduced down to a single line using a list comprehension
output = [float(e) for e in lst if 0 < float(e) < 100]
But now we need to use float(e) twice
We can use another list comprehension to make lst already a list of float
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = [float(e) for e in s.split()] # Now lst is a list of floats.
output = [e for e in lst if 0 < e < 100]
Since we only need to iterate lst once, a tiny change makes it a generator expression. So your final program could be
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = (float(e) for e in s.split()) # Now lst is a generator of floats.
output = [e for e in lst if 0 < e < 100]
print("The number between 0 and 100 are ", output)
Your current code has a couple of issues, assuming you're in Python 2.x.
Using input causes Python to try to evaluate the user input, which will cause problems because you want them to input a list of numbers. raw_input will just give you what the user input without trying to parse it.
list.append is in-place, which means that the side effect of the function call will simply perform the append on the object it is called on, instead of returning a new object.
Try this:
s = raw_input("Please enter a list of numbers: ")
lst = s.split()
output = []
for e in lst:
if float(e) > 0 and float(e) < 100 : # inbetween 0 and 100
output.append(float(e))
print("The number between 0 and 100 are ", output)
s = str(input("Please enter a list of numbers:"))
lst = s.split()
output = []
for e in lst:
if float(e) > 0 and float(e) < 100 :
output.append(float(e))
print("The number between 0 and 100 are ", output)
else:
print("The number less than 0 or greter than 100 ", e)
s = input("Please enter a list of numbers:")
output = [each for each in s if each > 0.0 and each < 100.0]
print("The number between 0 and 100 are ", output)

Categories