Reading a float value from standard input and using in time.sleep - python

I'm currently struggling with simple code, it works with seconds but I want to allow users to use minutes instead, which is much easier. Here it is:
import time
import os
import math
import subprocess
input1 = raw_input("Broj minuta:")
min = input1 * 60
min1 = float(min)
print min1
time.sleep(min1)
os.system("shutdown")
I get this error:
Broj minuta:2
Traceback (most recent call last):
File "timer.py", line 8, in <module>
time.sleep(min)
TypeError: a float is required
When I try to convert it to float using code below, it says that sleep time is big, and it is, if I choose 2 minutes I get:
min = input1 * 60
min1 = float(min)
Broj minuta:2
2.22222222222e+59
Traceback (most recent call last):
File "timer.py", line 10, in <module>
time.sleep(min1)
OverflowError: sleep length is too large

input1 = raw_input("Broj minuta:")
raw_input returns a string. You need to convert that to a number, like this
input1 = int(raw_input("Broj minuta:"))
If you don't do this, let say if you enter 2, it will still be a string and you are doing
input * 60
which means '2' * 60, which is equal to '222222222222222222222222222222222222222222222222222222222222' and it is still a string. That's why time.sleep(min) complains that
TypeError: a float is required
In the second case, you are converting '222222222222222222222222222222222222222222222222222222222222' to a float properly, but the value is 2.22222222222e+59, which is tooo big for time.sleep.

(Your traceback must be out of date; it shows time.sleep(min) (in which case the error is justified), but your code has time.sleep(min1).)
The issue is that the result of raw_input is a string. When you write input1 * 60, you repeat the string 60 times (i.e. instead of 120, you get '222222222222222222222222222222222222222222222222222222').

You're performing the conversion too late. input1 is a string, and multiplying a string by an integer
min = input1 * 60
does string repetition: '12' * 60 == '12121212...
Instead, convert to float, then multiply:
min = float(input1) * 60

The variable returned by raw_input is a string.
To add more information to what is happening in your code, here is an example session.
In [1]: i = raw_input("Something")
Something20
In [2]: i
Out[2]: '20'
In [3]: type(i)
Out[3]: str
In [4]: i*60
Out[4]: '202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020'
In [5]: float(i*20)
Out[5]: 2.02020202020202e+39
Out [2] shows the string '20'. This is confirmed when we check the type of i, which is str.
Now, in Python, when you multiply a string with a number x, you get a string with x times the original string repeated.
This is what was happening in your code. Thus, as suggested in the other answer, you need to cast your input to a float.
Another, way of doing this (on Python 2.x) is to NOT use raw_input() and instead use input()
In [6]: j = input('Something else?')
Something else?20
In [7]: j
Out[7]: 20
In [8]: j*60
Out[8]: 1200

Related

How to solve OverflowError when generating same random numbers between R and Python using SyncRNG

I am trying to reproduce R codes in Python and I have to generate same random numbers in both languages. I know that using the same seed is not enough to get same random numbers and reading one of the answers on this platform regarding this topic I have discovered that there exists: SyncRNG library, which generates same random numbers between R and Python. Everything looks fine as long as I have discovered that on Python 3.7.3 I can generate via SyncRNG just one number because as soon as you iterate the procedure, for instance, with a for loop you get this error:
OverflowError: Python int too large to convert to C long.
As I was mentioning:
>>> from SyncRNG import SyncRNG
>>> s = SyncRNG(seed=123)
>>> r = s.rand()
>>> r
0.016173338983207965
and as we can see it works. The method ".rand()" generates random numbers between zero and one.
But if I try to iterate:
>>> from SyncRNG import SyncRNG
>>> s = SyncRNG(seed=123)
>>> b = []
>>> for i in range(5):
temp = s.rand()
b.append(temp)
and I get this:
OverflowError: Python int too large to convert to C long
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<pyshell#41>", line 2, in <module>
temp = s.rand()
File "C:\Users\Stefano\AppData\Local\Programs\Python\Python37\lib\site-packages\SyncRNG\__init__.py", line 27, in rand
return self.randi() * 2.3283064365387e-10
File "C:\Users\Stefano\AppData\Local\Programs\Python\Python37\lib\site-packages\SyncRNG\__init__.py", line 22, in randi
tmp = syncrng.rand(self.state)
SystemError: <built-in function rand> returned a result with an error set
So, I humbly ask if someone is able to solve this problem. If I lost old answers about this topic I'm sorry, please link them in the answer section.
Thank you!
This is not a solution, but a workaround. The overflow bug is not reproducible on my system. The workaround:
from SyncRNG import SyncRNG
s = SyncRNG(seed=123)
ct = 0
b = []
while ct < 5:
try:
temp = s.rand()
b.append(temp)
ct += 1
except OverflowError:
pass
Performance will be compromised due to the try/except on each loop.

Convert numpy.float64 to integer

Im currently working on an assignment but have encountered a problem. How do I convert a numpy.float64 to integer.
import numpy as np
bike = np.loadtxt('Bike.txt')
def count_days(year, month, day):
year_2011=[31,28,31,30,31,30,31,31,30,31,30,31]
year_2012=[31,29,31,30,31,30,31,31,30,31,30,31]
if (year == 2011):
days= sum(year_2011[:(month-1)])+day
else:
days= 365+sum(year_2012[:month-1])+day
return days
bike_2011 = bike[count_days(2011, 0, 0)-1]
bike_2012 = bike[count_days(2012, 0, 0)-1]
int(bike_2011)
int(bike_2012)
for e in len(bike_2012):
if bike[e] > 8000 : print (bike [e], x)
This returns the following error.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-f111e601c474> in <module>
1 bike_2012.astype(int)
----> 2 for e in len(bike_2012):
3 if bike[e] > 8000 : print (bike [e], x)
TypeError: object of type 'numpy.float64' has no len()
Replacing bike = np.loadtxt('Bike.txt') with bike = np.loadtxt('Bike.txt').astype(int) should do the trick. And while you're at it, you should delete int(bike_2011) and int(bike_2012) -- these do absolutely nothing.
On the other hand, you program has more severe problems, count_days returns a single number, so bike_2011 and bike_2012 are a plain variables, not lists or tuples, so trying to do len(bike_2011) will give you the same error, no matter if bike_2011 is integer or float. You cannot take a length of a float (or integer).

TypeError: not all arguments converted during string formatting 11

def main():
spiral = open('spiral.txt', 'r') # open input text file
dim = spiral.readline() # read first line of text
print(dim)
if (dim % 2 == 0): # check to see if even
dim += 1 # make odd
I know this is probably very obvious but I can't figure out what is going on. I am reading a file that simply has one number and checking to see if it is even. I know it is being read correctly because it prints out 10 when I call it to print dim. But then it says:
TypeError: not all arguments converted during string formatting
for the line in which I am testing to see if dim is even. I'm sure it's basic but I can't figure it out.
The readline method of file objects always returns a string; it will not convert the number into an integer for you. You need to do this explicitly:
dim = int(spiral.readline())
Otherwise, dim will be a string and doing dim % 2 will cause Python to try to perform string formatting with 2 as an argument:
>>> '10' % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>>
Also, doing print(dim) outputed 10 instead of '10' because print automatically removes the apostrophes when printing:
>>> print('10')
10
>>>

why this python code is producing Runtime Error in ideone?

import sys
def func():
T = int(next(sys.stdin))
for i in range(0,T):
N = int(next(sys.stdin))
print (N)
func()
Here I am taking input T for for loop and iterating over T it gives Runtime error time: 0.1 memory: 10088 signal:-1 again-again . I have tried using sys.stdin.readline() it also giving same error .
I looked at your code at http://ideone.com/8U5zTQ . at the code itself looks fine, but your input can't be processed.
Because it is:
5 24 2
which will be the string:
"5 24 2"
this is not nearly an int, even if you try to cast it. So you could transform it to the a list with:
inputlist = next(sys.stdin[:-2]).split(" ")
to get the integers in a list that you are putting in one line. The loop over that.
After that the code would still be in loop because it want 2 integers more but at least you get some output.
Since I am not totally shure what you try to achieve, you could now iterate over that list and print your inputs:
inputlist = next(sys.stdin[:-2]).split(" ")
for i in inputlist
print(i)
Another solution would be, you just put one number per line in, that would work also
so instead of
5 24 2
you put in
5
24
2
Further Advice
on Ideone you also have an Error Traceback at the bottom auf the page:
Traceback (most recent call last):
File "./prog.py", line 8, in <module>
File "./prog.py", line 3, in func
ValueError: invalid literal for int() with base 10: '1 5 24 2\n'
which showed you that it can't handle your input

How to treat numbers in list as integers in function

I'm trying to write a function that finds both the signed/unsigned max/min values given a bit length. But every time I execute the function I get an error, here is my code
#function to find max and min number of both signed and unsigned bit values
def minmax (n) :
for numbers in n :
unsignedmax = (2**n)-1
unsignedmin = 0
signedmax = 2**(n-1)-1
signedmin = -2**(n-1)
print "number ", "unsigned ", "signed"
#Main
bitlist = [2, 3, 8, 10, 16, 20, 32]
minmax(bitlist)
the error is
Traceback (most recent call last):
File "C:/Users/Issac94/Documents/Python Files/sanchez-hw07b.py", line 23, in <module>
minmax(bitlist)
File "C:/Users/Issac94/Documents/Python Files/sanchez-hw07b.py", line 6, in minmax
unsignedmax = (2**n)-1
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'list'
>>>
I wasn't done writing it but ran it to make sure there was no error in the logic part but i get that one error when trying to find the values. Is there maybe a way to insert int() or something similar to have the number be treated as type integer and not tyle list which im assuming is happening?
Change the method definition and first line to this:
def minmax (numbers) :
for n in numbers :
That is, in these two lines, replace 'n' with 'numbers' everywhere it appears and replace 'numbers' with 'n' where it appers.
As you have it written the variable "numbers" holds the item in the list you want to process and the variable "n" is holding the list. But the rest of your code is written with the reverse assumption.

Categories