Python: a type error - python-3.4

So here is my situation. Ive been trying to make a advanced calculator in python 3.4, one where you can just type something like this. '1 + 1', and it would then give you the answer of '2'. Now i will explain how my calculator is supposed to work. So you start by entering a maths equation, then it counts the words you entered based on the spaces. It does this so it knows how long some future loops need to be. Then it splits up everything that you entered. It splits it up into str's and int's but its all still in the same variable and it's all still in order. The thing i'm having trouble with is when it is meant to actually do the calculations.
here is all of my code-
# This is the part were they enter the maths equation
print("-------------------------")
print("Enter the maths equation")
user_input = input("Equation: ")
# This is were it counts all of the words
data_count = user_input.split(" ")
count = data_count.__len__()
# Here is were is splits it into str's and int's
n1 = 0
data = []
if n1 <= count:
for x in user_input.split():
try:
data.append(int(x))
except ValueError:
data.append(x)
n1 += 1
# And this is were it actually calculates everything
number1 = 0
number2 = 0
n1 = 0
x = 0
answer = 0
while n1 <= count:
#The code below checks if it is a number
if data[n1] < 0 or data[n1] > 0:
if x == 0:
number1 = data[n1]
elif x == 1:
number2 = data[n1]
elif data[n1] is "+":
if x == 0:
answer += number1
elif x == 1:
answer += number2
n1 += 1
x += 1
if x > 1:
x = 0
print("Answer =", answer)
but during the calculation it messes up and gives me and error
error-
if data[n1] < 0 or data[n1] > 0:
TypeError: unorderable types: str() < int()
can anyone see what i am doing wrong here?
Thanks

When you are comparing a string and an integer, this problem comes.
Python doesn't guess, it throws an error.
To fix this, simply call int() to convert your string to an integer:
int(input(...))
So, corrected statement should be:
if int(data[n1]) < 0 or int(data[n1]) > 0:

Related

Runtime Error in Google Kick start using python

I am practicing 'Round D 2020 - Kick Start 2020' though I have properly done coding for Record Breaker problem and also showing correct answers for sample test cases still I am getting RE (Runtime error).
See attached screenshot and code.
enter image description here
T=int(input())
rlst=[]
if "\n" in T:
T
for i in range(T):
N=int(input())
V=input()
V_lst=V.split()
rbday=0
high_day=V_lst[0]
if V_lst[0] > V_lst[1]:
rbday=rbday+1
high_day=V_lst[0]
for n in range(1,N-1):
if ((V_lst[n] > V_lst[n-1]) and (V_lst[n] > V_lst[n+1]) and (V_lst[n] > high_day)) :
high_day=V_lst[n]
rbday=rbday+1
rlst.append(rbday)
for i in range(T):
print("Case {}# {}".format(i+1,rlst[i]))
The error is in this line: if V_lst[0] > V_lst[1]:, because you didn't consider the case where N is equal to 1, so this V_lst[1] is out of index.
I can share my solution, using Python 3.7 too:
T = int(input())
for case in range(1, T+1):
N = int(input())
V = list(map(int, input().split()))
n_breaks = 0
d = 0 #It's like previous high day in your code.
for i in range(N):
if N == 1:
n_breaks = 1
break
if i != N-1:
if V[i] > d and V[i] > V[i+1]:
n_breaks += 1
d = V[i]
else:
if V[i] > d and V[i] > V[i-1]:
n_breaks += 1
print(f"Case #{case}: {n_breaks}")

Error in for loop - attempt to select less than one element in integerOneIndex

I'm trying to translate a C routine from an old sound synthesis program into R, but have indexing issues which I'm struggling to understand (I'm a beginner when it comes to using loops).
The routine creates an exponential lookup table - the vector exptab:
# Define parameters
sinetabsize <- 8192
prop <- 0.8
BP <- 10
BD <- -5
BA <- -1
# Create output vector
exptab <- vector("double", sinetabsize)
# Loop
while(abs(BD) > 0.00001){
BY = (exp(BP) -1) / (exp(BP*prop)-1)
if (BY > 2){
BS = -1
}
else{
BS = 1
}
if (BA != BS){
BD = BD * -0.5
BA = BS
BP = BP + BD
}
if (BP <= 0){
BP = 0.001
}
BQ = 1 / (exp(BP) - 1)
incr = 1 / sinetabsize
x = 0
stabsize = sinetabsize + 1
for (i in (1:(stabsize-1))){
x = x + incr
exptab [[sinetabsize-i]] = 1 - (BQ * (exp(BP * x) - 1))
}
}
Running the code gives the error:
Error in exptab[[sinetabsize - i]] <- 1 - (BQ * (exp(BP * x) - 1)) :
attempt to select less than one element in integerOneIndex
Which, I understand from looking at other posts, indicates an indexing problem. But, I'm finding it difficult to work out the exact issue.
I suspect the error may lie in my translation. The original C code for the last few lines is:
for (i=1; i < stabsize;i++){
x += incr;
exptab[sinetabsize-i] = 1.0 - (float) (BQ*(exp(BP*x) - 1.0));
}
I had thought the R code for (i in (1:(stabsize-1))) was equivalent to the C code for (i=1; i< stabsize;i++) (i.e. the initial value of i is i = 1, the test is whether i < stabsize, and the increment is +1). But now I'm not so sure.
Any suggestions as to where I'm going wrong would be greatly appreciated!
As you say, array indexing in R starts at 1. In C it starts at zero. I reckon that's your problem. Can sinetabsize-i ever get to zero?

On submission it is giving runtime_error

t=int(input())
while t>0 :
c=0
n,h,y1,y2,e = list(map(int, input().split()))
for i in range(n):
x0,x1 = list(map(int, input().split()))
if x0==1 :
if x1 < h-y1:
e -= 1
else :
if y2 < x1 :
e -= 1
if e>0 :
c+=1
else :
break
print(c)
t-=1
It is passing the sample test cases but on submission, it is showing runtime error(NZEC) occurred.
Here is the link to the question: https://www.codechef.com/problems/PIPSQUIK
The problem is that you're reading the inputs and processing them simultaneously. So, a situation can arise in some test cases such that e<=0 but you still have some x0 x1 to read(i.e. i<n-1). In such cases, you'll break the loop because e<=0 and in next iteration of while loop, you'll try to read 5 values n,h,y1,y2,e = list(map(int, input().split())) but you'll receive only 2 values x0 x1 and hence it'll throw a ValueError: not enough values to unpack (expected 5, got 2) and hence it'll not pass all the test cases.
To fix this, just take all inputs first and then process them according to your current logic.
t=int(input())
while t>0 :
c=0
n,h,y1,y2,e = list(map(int, input().split()))
inputs = []
for i in range(n):
inputs.append(list(map(int, input().split())))
for inp in inputs:
x0,x1 = inp
if x0==1 :
if x1 < h-y1:
e -= 1
else :
if y2 < x1 :
e -= 1
if e>0 :
c+=1
else :
break
print(c)
t -= 1

Number addition in Lua - avoiding negative values

This is not hardcore math but I simply cannot find the correct function to make this in a smooth way.
Lets say I have 3 values. Cost1 Cost2 Cost3. Each have a value, I want to add them together into a final number, TotalCost.
Cost1+Cost2+Cost3 = TotalCost
Problem is, if any of Cost1/2/3 is negative, I want to make that a ZERO, ie;
Cost1 = -100
Cost2 = 50
Cost3 = 150
Cost1+Cost2+Cost3 = TotalCost
equals
0 + 50 + 150 = 200
I know I have seen something with like (X*Math.Floor * 100) / 100 , to do just this, if im not completly mistaken.
Would be greatly apreciated if anyone could answer. I know its a basic question but I simply couldent figure out how (with a smart way that is) with the Math. functions.
Im coding in Lua: http://lua-users.org/wiki/MathLibraryTutorial
Possibly the shortest way to do this is math.max(x,0). So your expression would be:
math.max(Cost1,0) + math.max(Cost2,0) + math.max(Cost3,0)
Of course, you could also make a function out of it -- and you probably should, if you're going to use it for more than a one-liner.
The most straight-forward way is to use if statements to test if a number is negative.
This is another way:
function my_sum(...)
sum = 0
for k, v in ipairs{...} do
sum = sum + (v > 0 and v or 0)
end
return sum
end
print(my_sum(-50, 50, 100)) -- 150
The expression v > 0 and v or 0 has a value of v if v > 0 is true, 0 otherwise.
Just write exactly what you said in Lua instead of English:
(Cost1 > 0 and Cost1 or 0) + (Cost2 > 0 and Cost2 or 0) + (Cost3 > 0 and Cost3 or 0)
You can simply do something like this:
local value1 = 100
local value2 = -200
local value3 = 200
local value4 = (value1 > 0 and value1 or 0) + (value2 > 0 and value2 or 0) + (value3 > 0 and value3 or 0)
The nicest way would be to implement a function that sums up non-negative values
function sumOfPositives(tableOfValues)
local sum = 0
for i,v in ipairs(tableOfValues) do
sum = sum + v > 0 and v or 0
end
return sum
end
This way you can do it for any number of values.
If you prefer to just enter the values without having them in a table you can do what Yu Hao suggested and use the ... argument.

Python Programming While Loop

Hi I'm new to python and programming in general. I am trying write a program that uses a while loop to add integers from 1 to the number entered. the program also has to give an error statement if the user enters a 0 or negative number. So far the integers add up and the error statement works but the program is not looping, it only asks the user to input a number one time. Please help. This is my source code so far. Thanks
x = int(input("Enter a positive number not including zero:" ))
total = 0
n = 1
while n <= x:
total = total + n
n = n + 1
# prints the total of integers up to number entered
print("Sum of integers from 1 to number entered= ",total)
if x <= 0 or x == -x:
print ("invalid entry")
Try this code...
op='y'
while op=='y':
x = int(input("Enter a positive number not including zero:" ))
total = 0
n = 1
if x > 0:
while n <= x:
total = total + n
n = n + 1
# prints the total of integers up to number entered
print("Sum of integers from 1 to number entered= ",total)
else:
print ("invalid entry")
op = raw_input("Are you want to continue this operation (y/n):" )
Put your whole code this way
done = False
while not done:
//your entire code here except the last 2 lines
if x > 0:
done = True

Resources