Reading numbers in Python - 'str' object cannot be interpreted as an integer - python

I have a problem with the code. I have a sort algorithm and I check it for a specific input.
As input, the number of tests 1 <= d <= 100, the integer 0 <n <= 214748364 and n numbers from the range -2147483646 <= a_k <= 2147483647.
Input:
3
8 5 2 6 4 1 3 2 6
8 2 4 5 6 1 3 2 6
8 1 6 2 7 3 8 4 5
My code:
# Bubble Sort
d = int(input()) #number of tests
#A = []
def wczytanie_liczb():
for k in range(0,d):
n = input() #number of digits in the string
n = int(n)
A = []
for l in range(0,n):
m = input() #fill in the array
m = int(m)
A.append(m)
#print(A)
bubble_sort(A)
def bubble_sort(A):
i = 0
zam = True
while i < len(A)-1 and zam:
j = 0
zam = False
while j < len(A) - 1 - i:
if A[j] > A[j+1]:
A[j], A[j+1] = A[j+1], A[j]
zam = True
j +=1
#print(A)
wczytanie_liczb()
it gives an error:
Traceback (most recent call last):
File "./prog.py", line 28, in <module>
File "./prog.py", line 9, in wczytanie_liczb
TypeError: 'str' object cannot be interpreted as an integer

Conclusion. The “TypeError: 'str' object cannot be interpreted as an integer” error is raised when you pass a string as an argument into a range() statement. To fix this error, make sure all the values you use in a range() statement are integers

Related

Find index of less or equal value in list recursively (python)

Got task to find indexes of value and double that value in input list.
In input first line we get list range, second - list of values, third - value to find.
The output is 2 numbers - indexes of equal or higher value and double the value. If there is none, return -1
Example input:
6
1 2 4 4 6 8
3
Example output:
3 5
What i got so far is standart binary search func, but i dont get how to make it search not only for exact number but nearest higher.
def binarySearch(arr, x, left, right):
if right <= left:
return -1
mid = (left + right) // 2
if arr[mid] >= x:
return mid
elif x < arr[mid]:
return binarySearch(arr, x, left, mid)
else:
return binarySearch(arr, x, mid + 1, right)
def main():
n = int(input())
k = input().split()
q = []
for i in k:
q.append(int(i))
s = int(input())
res1 = binarySearch(q, s, q[0], (n-1))
res2 = binarySearch(q, (s*2), q[0], (n-1))
print(res1, res2)
if __name__ == "__main__":
main()
The input is:
6
1 2 4 4 6 8
3
And output:
3 4
Here's a modified binary search which will return the base zero index of a value if found or the index of the next highest value in the list.
def bsearch(lst, x):
L = 0
R = len(lst) - 1
while L <= R:
m = (L + R) // 2
if (v := lst[m]) == x:
return m
if v < x:
L = m + 1
else:
R = m - 1
return L if L < len(lst) else -1
data = list(map(int, '1 2 4 4 6 8'.split()))
for x in range(10):
print(x, bsearch(data, x))
Output:
0 0
1 0
2 1
3 2
4 2
5 4
6 4
7 5
8 5
9 -1

Why does program count one extra value (cycle "while")?

Why the program count one more value? For example, I give him N = 50. It gives out:
1
4
9
16
25
36
49
64
Code:
N = int(input())
n = 1
k = 1
while n < N:
n = k ** 2
print(n)
k = k + 1
As explained, you're checking n then changing n, you want to change n then check before continuing.
You can use the walrus operator to assign n and check it's value all in the while statement. (requires Python 3.8+)
N = int(input())
n = 1
k = 1
while (n := k**2) < N:
print(n)
k += 1
This essentially assigns n to k**2 then checks if that result is <N before continuing.
1
4
9
16
25
36
49
Your program outputs 1 4 9 16 25 36 49 64 if your input is 50 because the `while`` loop is checking the value before you increase it. Once in the loop, you increase it, calculate the square and then print.
If you want it to terminate, try setting calculating n as the last step in the loop:
N = int(input())
n = 1
k = 1
while n < N:
print(n)
k = k + 1
n = k ** 2
You're checking whether you reached the limit before you calculate the square and print it. So you're checking the previous value of n, not the one that's about to be printed.
Move the check inside the loop.
while True:
n = k ** 2
if n >= N:
break
print(n)
k += 1
The n < N is evaluated after you've changed (and printed) n.
n = 1
k = 1
N=50
while 1:
n = k ** 2
if n > N:
break
print(n)
k = k + 1
To fix this, break before you print, moving the evaluation inside the loop rather than after the last update of n
1
4
9
16
25
36
49
With the condition of your code, for example, when n = 49, The condition is fulfilled because 49 < 50 therefore it will continue to process the value and print the new one. But once n = 64 which is > 50, it stops. This is a possible solution:
N = int(input())
n = 1
k = 1
while True:
if n >= N:
break
n = k ** 2
print(n)
k = k + 1
This will continuously execute the code but once the condition is met that n >= N, it will stop executing.

I am not able to understand how the output of the program is 3

num = 0
for i in range(5,0,-1):
num+= i > num
print(num)
When I ran the program it was displaying the output as 3. I am not able to understand how 3 is the output
num = 0
for i in range(5,0,-1): #Loop 5 to 1
num+= i > num # for first 3 steps ( i > num) = True = 1, i.e add 1 to num
# for remaining steps (i > num) = False = 0, i.e add 0 to num
print(i,num)
print(num)
output
5 1
4 2
3 3
2 3
1 3
3
Look at what happens inside the loop:
num = 0
for i in range(5,0,-1):
print(f'num:{num}, i:{i}, i>num:{i>num} >>> num+(i>num):{num}+{i>num}', end='=')
num+= i > num
print(f'{num}')
#print(num)
Output:
num:0, i:5, i>num:True >>> num+(i>num):0+True=1
num:1, i:4, i>num:True >>> num+(i>num):1+True=2
num:2, i:3, i>num:True >>> num+(i>num):2+True=3
num:3, i:2, i>num:False >>> num+(i>num):3+False=3
num:3, i:1, i>num:False >>> num+(i>num):3+False=3
you are checking the condition if i > num every time you increment. Here, you are not incrementing i, instead the condition i>num , which return True when i> num and increment 1 each time the condition is True.
you add to num the boolean value of i > num. in python, True is 1 and False is 0.
if you follow this logic you will see that the expression returns 1 3 times
num = 0
for i in range(5,0,-1):
num+= i > num # this line similar to num = num + (i > num)
print(num)
if i > num yeilds to True then it is equal to 1 so, thennum = num + 1
else i > num yeilds to False then it is equal to 0 so, then num = num + 0
The result of the relation (i > num) evaluated to 0/1 (True/False). Adding print to the body of the loop it may be clearer for you:
num = 0
for i in range(5,0,-1):
num+= i > num
print("i: {}, num: {}".format(i, num))
print(num)
And the output:
i: 5, num: 1
i: 4, num: 2
i: 3, num: 3
i: 2, num: 3
i: 1, num: 3
3
This loop will execute for 5 times .And i 's value will be "5 4 3 2 1"
i > num will producre , boolean values. when True it will be treated as 1 and when False 0.
So you will get 3 "True" values and 2 "False" values .Hence result is 3, which is outputed.

Error in my code in python 3 (coin change problem)

This is the error:
Message File Name Line Position
Traceback
34
count 25
TypeError: unsupported operand type(s) for -: 'int' and 'str'
The code can be found here:
import sys
N = int(sys.stdin.readline()) #4
munten = [] #1, 2, 5, 10
for p in range(0, N):
munten.append(sys.stdin.readline())
bedrag = int(sys.stdin.readline()) #13
m = len(munten)
def count(S, m, bedrag):
table = [[0 for x in range(m)] for x in range(bedrag+1)]
for i in range(m):
table[0][i] = 1
for i in range(1, bedrag+1):
for j in range(m):
x = table[i - S[j]][j] if i-S[j] >= 0 else 0
y = table[i][j-1] if j >= 1 else 0
table[i][j] = x + y
return table[bedrag][m-1]
print(count(munten, m, bedrag)) #output = 16
The inputs: N = 4 (amount of coins in array), (the array) munten = (1, 2, 5, 10), (amount to pay) bedrag = 13 --> (amount of combinations I can pay with the coins in the array) output = 16
munten are list of strings in your code.
for p in range(0, N):
munten.append(int(sys.stdin.readline()))
Execution example
> python3 sample.py
> 4 #N
> 1 #munten0
> 2 #munten1
> 5 #munten2
> 10 #munten3
> 13 #bedrag
16

How do I reduce the number of loops or complexity

So what I am trying to do is to find count of alternating numbers such that it alternates with -ve and positive sign
for eg: 1 -2 3 -4 would get me 4 3 2 1 as from 1 to -4 including the two numbers there are 4 numbers.
Simillarly for 1 1 -3 2 would get me 1 3 2 1
Now I have the code but I cannot optimise it and it returns me a time limit exceeded error even though it works for moderate input stream.
j=0
count=0
length=(raw_input())
st=map(int,raw_input().split())
while j+1 < len(st):
k=j+1
count=0
temp=j
while k<len(st) and ((st[k]<0 and st[j]>0) or (st[k]>0 and st[j]<0)):
count+=1
k+=1
j+=1
print count+1,
j=temp+1
print 1
Try using for loops instead of while loops as that avoids you some variable assignments:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
if (st[j]<0 and st[j+1]>0) or (st[j+1]<0 and st[j]>0):
count += 1
else:
break
print(count)
print(1)
This will give:
<< 1 -2 3 4
>> 4
>> 3
>> 2
>> 1
<< 1 1 -3 2
>> 1
>> 3
>> 2
>> 1
It may also be a bit faster if you extract the numbers from the list once instead of twice:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
first, second = st[j:j+2]
if (first<0 and second>0) or (first>0 and second<0):
count += 1
else:
break
print(count)
print(1)
The last thing I would try is checking that they sigs are different with a single comparisson but I do not really expect this to be faster:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
product = st[j] * st[j+1]
if product != abs(product):
count += 1
else:
break
print(count)
print(1)

Categories