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
Related
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
how can i print the matrix[i][j]?
from array import *
class Sudoku :
matrix = []
x = -1
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a)
except:
matrix.append(x)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])
error is :
print(matrix[i][j])
TypeError: 'int' object is not subscriptable
You can use this code if you want to complete the code with minimum number of lines but it sure is a bit complex.
m,n=input("Enter num of rows and columns:").split()
matrix=[[int(input()) for y in range(int(n))]for x in range(int(m))]
[[[print(matrix[i][j], end=" ") for j in range(int(n))] and print(" ") ]for i in range(int(m))]
The output looks like this:
Enter num of rows and columns: 3 3
1
2
3
4
5
6
7
8
9
1 2 3
4 5 6
7 8 9
from array import *
class Sudoku:
matrix = []
x = -1 # <--- 4
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a) # <--- 11
except: # <--- 12
matrix.append(x) # <--- 13
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j]) # <--- 16
Let's look at the code. If except at L12 is catched, x, which is -1 (L4) is appended. So at L16, when matrix[i] evaluates to -1, -1[j] is an error.
There's also another problem -- L11 will never be executed, because a is always a list, not int.
matrix = [] is declaring matrix to be a list. But you are thinking of the matrix as having i,j locations like in math.
You have two options:
Option1: Map the list to a matrix
If you have a 3x3 matrix you have 9 locations, so
matrix = [0, 1, 2, 3, 4, 5, 6, 7, 8] is equivalent to
0 1 2
matrix = 3 4 5
6 7 8
so if wanted to print out this matrix you have to do some math to access the elements
for i in range(3): # i = 0, 1, 2
for j in range(3): # j = 0, 1, 2
print(matrix[3*i + j], end=" ")
print("")
Option2: Make matrix be a nested list
have matrix becomes a list of row, and each row is a list of elements
matrix = []
x = -1
for i in range(0, 10):
row = []
for j in range(0, 10):
while True:
x = int(input(f"Enter matrix[{i}][{j}]} element: "))
if (isinstance(x, int)) == True :
row.append(x)
break;
matrix.append(row)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])
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
I have a task to make a program that will sum the first 100 Fibonacci numbers. I checked my output in Python, and my output in QBasic 64 and they aren't same. I checked with different inputs also.
Input: 10
Output: 89
-----------
Input: 100
Output: 573147844013817084101
Is it correct ?
Here is my code:
n = int(input())
print()
p = 0
d = 1
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
for i in range(n - 2):
p = d
d = z
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
print('Sum:', z)
EDIT: Code edited again, check it now. I just found on Wikipedia.. It depends from what number you start the loop. So if I use (0, 1, 1, 2, 3, 5, 8, 13, 21, and 34) as first 10 Fibonacci numbers, the sum is going to be 88, not 89.
The sums of the first ten and 100 fibonacchi number would be 88 and 573147844013817084100, respectively:
>>> cache = {}
>>> def fib(n):
if n == 0: return 0
if n == 1: return 1
if not n in cache:
cache[n] = fib(n - 1) + fib(n - 2)
return cache[n]
>>> sum([fib(i) for i in range(10)])
88
>>> sum([fib(i) for i in range(100)])
573147844013817084100
In your loop you are already starting the iteration at the 3rd position, since you set. So set your range to (n -2).
0: 1
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5
To get the sum of the Fibonacci numbers, using zero as the first in the series, you need to do this:
def run_it(n):
N2 = 0
N1 = 0
N = 0
z = N
for i in range(n):
print(N,z)
N2 = N1
N1 = N
if N is 0: N = 1
else: N = N1 + N2
z = z + N
run_it(int(input('Number: ')))
To calculate the sum using one as the start of the series, change the initial value of N from zero to one.
I am trying to make a spiral that looks like this
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
this is my code and it prints out a matrix but the numbers start on the outside and work in which is the opposite of what I want. How can I change this?
def main():
spiral = open('spiral.txt', 'r') # open input text file
dim = int(spiral.readline()) # read first line of text
num = int(spiral.readline()) # read second line
spiral.close()
print(dim)
if dim % 2 == 0: # check to see if even
dim += 1 # make odd
print(dim)
print(num)
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
x, y, c = 0, -1, 1
m = [[0 for i in range(dim)] for j in range(dim)]
for i in range(dim + dim - 1):
for j in range((dim + dim - i) // 2):
x += dx[i % 4]
y += dy[i % 4]
m[x][y] = c
c += 1
print(m)
print('\n'.join([' '.join([str(v) for v in r]) for r in m]))
print(num)
main()
replace
m[x][y] = c
by
m[x][y] = dim**2 + 1 - c
which basically counts backwards. Also you might want to have proper spacing with:
print('\n'.join([' '.join(["{:2}".format(v) for v in r[::-1]]) for r in m]))