I am very new to programming and Python!
for i in range(0.6):
print(i)
I am getting error:
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
for i in range(0.6):
TypeError: 'float' object cannot be interpreted as an integer
Range takes in two values, not a single float!
It should be
for i in range(0,6):
print(i)
this would give you
0
1
2
3
4
5
or just range(6)
You probably meant this:
for i in range(0,6):
print(i)
You need to change period to comma. Also, you need to indent the print statement.
You probably mistyped, and meant to put a comma instead of a dot:
for n in range(0,6):
print(n)
actually, the '0' in range() is not even needed, you can also do this, and it will print the same thing:
for n in range(6):
print(n)
both would output:
0
1
2
3
4
5
Related
I feel dum cuz I was trying to make a simple loop for a matrix to show differents solves and I couldn't fix the index of the array: (FOA I am using the Jupyter Notebook with SageMath 9.3)
A=random_matrix(ZZ,4,4)
k=srange(2,7)
show(k)
i=0
for i in k:
show(A^k[i])
show(k[i])
And I receive that:
[2,3,4,5,6]
"The matrix"
4
"The matrix"
5
"The matrix"
6
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-7-c50cd3e70a78> in <module>
4 i=Integer(0)
5 for i in k:
----> 6 show(A**k[i])
7 show(k[i])
IndexError: list index out of range
How can I print in the right order the k esponent 2,3,4,5,6?
If you add a show(i) call, you'll see the value of i each time is:
2
3
4
5
6
So k[i] is getting the third element of k, then the fourth, etc. That's what you're seeing when you show(k[i]). There's only five elements in the list, so when i=5, you'll get an IndexError as you've seen.
Instead, just use i:
A=random_matrix(ZZ,4,4)
k=srange(2,7)
show(k)
i=0
for i in k:
show(A**i)
show(i)
i tried to use for loop to iterate through the length of input (string) but when i tried using len() OR range() they gave me error saying that the type is wrong.
this code is a start of Cows and Bulls game.
tried changing object type to list.
switched between sublime text and idle.
i checked the type of the input using the type() method
import random
target = [random.randint(0, 9) for i in range(4)]
turns = 0
all_cows = False
while not all_cows:
guess = input('Cows and Bulls!\nguess 4 numbers: ')
turns += 1
#tried doing range(guess) does not work! *type of guess is string
#len(guess) - error cant iterate through int
#range(guess) error cannot be interpreted as an integer
for item in len(guess):
if guess[item] == target[item]:
print('cow')
elif guess[item] in target:
print('bull')`
Program output:
Cows and Bulls!
guess 4 numbers: 1111
Traceback (most recent call last):
File "D:\Computers\Programming\Python\Codes\Exercises\17.py", line 8, in <module>
for item in len(guess):
TypeError: 'int' object is not iterable
Cows and Bulls!
guess 4 numbers: 1111
Traceback (most recent call last):
File "D:\Computers\Programming\Python\Codes\Exercises\17.py", line 8, in <module>
for item in range(guess):
TypeError: 'str' object cannot be interpreted as an integer
You need to combine range() and len(). By using
for index in range(len(guess)):
# your code here
you can iterate over the length of the guess.
You can also directly iterate over guess, but since you also need the index of each character, you need to use enumerate(). This will return two values for each character, the first is the index, the second is the character itself. So you would do:
for index, c in enumerate(guess):
# your code here with index as the index and c as the character
input() Function in python3 takes eac value as str
So you need to convert it into int by using int() Function
Check with following Code :
import random
target = [random.randint(0, 9) for i in range(4)]
turns = 0
all_cows = False
while not all_cows:
guess = input('Cows and Bulls!\nguess 4 numbers: ')
turns += 1
#Iterate String Directly
for item in guess:
#Convert Substring into int for using as Indices
if guess[int(item)] == target[int(item)]:
print('cow')
elif guess[int(item)] in target:
print('bull')
Thanks everyone for helping my out on that case.
seems like the problem is in me not understanding len() right, i forgot it returns the length as int and got confused when the err said object type int.
solution 1: using range(len(guess)) to iterate through through the length of the string.
solution 2: iterating through the string directly - wasn't what i searched for since i wanted to use the 'item' to index the string.
solution 3: using enumerate(guess) which i never heard of (so if someone is bored and want to explain it ill accept the explanation gratefully!
edit: got my answer.
Your problem is that your guess acquired by input is of type string (as are inputs). Then, the type of len(guess) is obviously int. You can't iterate over an int as it is not a sequence. You have a few options to overcome this problem:
iterate over the indices using range:
for i in range(len(guess)):
if int(guess[i]) == target[i]:
you could use enumerate:
for i, c in enumerate(guess):
if int(c) == target[i]:
Turn your input from the user to a list of ints:
guess = input('Cows and Bulls!\nguess 4 numbers: ')
guesses = [int(c) for c in guess]
for i in range(len(guess)):
if guess[i] == target[i]:
could also be done using map: guesses = list(map(int, guess))
I try to run this program but it has the following error:
Traceback (most recent call last):
File "C:/Users/Αλέξανδρος/Desktop/1.py", line 12, in <module>
k=k+C[s]
IndexError: list index out of range
The code is below
a=0
b=0
s=0
k=0
A = [0 for a in range(1000)]
B = [0 for b in range(1000)]
C = [0 for s in range(1000000)]
while a<=1000:
C[s]=(A[a]**2+B[b]**2)**0.5
a=a+1
s=s+1
k=k+C[s]
if a==1000:
b=b+1
a=0
if a==1000 and b==1000:
print (k/1000000)
I know that this question is probably duplicated, but I don't know how to solve it, because in the beggining I thought that the error is because C[-1] doesn't exist. But I don't think that is the problem.
Thank you in advance
Because of a<=1000 you code executes 1,000,001 iterations, but there are only 1,000,000 elements in the list. You made a classical "off by 1" mistake. Change <= to <.
Indeed, you should be using numpy for problems like this.
You are acessing past the array range, but just changing <= to < won't fix it as it will still execute
s=s+1
k=k+C[s]
in the iteration where s=999999 and it breaks when trying to access C[1000000].
You can easily debug the values on the iteration where it breaks by adding a print:
#!/usr/bin/python3
a=0
b=0
s=0
k=0
A = [0 for a in range(1000)]
B = [0 for b in range(1000)]
C = [0 for s in range(1000000)]
while a<=1000:
print("a={:d} b={:d} s={:d}".format(a,b,s))
C[s]=(A[a]**2+B[b]**2)**0.5
a=a+1
s=s+1
k=k+C[s]
if a==1000:
b=b+1
a=0
if a==1000 and b==1000:
print (k/1000000)
And you will get your culprit:
(...)
a=997 b=999 s=999997
a=998 b=999 s=999998
a=999 b=999 s=999999
Traceback (most recent call last):
File "./off.py", line 15, in <module>
k=k+C[s]
IndexError: list index out of range
Regarding your algorithm, the s=s+1 / k=k+C[s] lines should probably be reversed (you want to accumulate in k the latest C[s] computed, C[s+1] is always 0 as it will only be computed by the next iteration.
I apologize ahead of time for the basic nature of this question but I could really use a different set of eyes to see why I'm still getting an IndexError: list index out of range.
Here is my code:
def longestRun(L):
counter=1
ii=0
counts=[1]
while ii<=max(range((len(L)))):
if L[ii] <= L[(ii+1)]:
counter+=1
ii+=1
else:
ii+=1
counts.append(counter)
counter=1
continue
counts.sort()
return counts[-1]
It is supposed to count the longest streak of consecutive increases for a list of integers. I got it working by subtracting 1 from the while statement but then it will not always show the right answer because it won't go through the whole list.
Here is my specific error message:
IndexError
Traceback (most recent call last)
<ipython-input-76-1b4664f2fb31> in <module>()
----> 1 longestRun(L)
C:\Users\james_000\Desktop\longestRun.py in longestRun(L)
4 counts=[1]
5 while ii<=max(range((len(L)))):
----> 6 if L[ii] <= L[(ii+1)]:
7 counter+=1
8 ii+=1
Your while loop is while ii<=max(range((len(L)))): and then your if statement's condition accesses L[ii+1] which runs off the end of the array.
It's simple math. Let's say L is of length 10. That makes the last index 9. ii can eventually be 9, thus ii+1 is going to be out of range.
Just starting problem 164 for project euler, and i want a function to output a list of the sum of each set of 3 consecutive digits in a 20 digit number. Here is my function.
def func(n):
sumlist = []
m = str(n)
for i in range(0,18):
sumlist.append(sum(int(m[i])+int(m[i+1])+int(m[i+2])))
return sumlist
I keep getting the iteration over non sequence error and i can't figure out why i should. Any help would be appreciated, thanks.
EDIT
The full traceback is:
Traceback (most recent call last):
File "peproblem164.py", line 8, in ? print func(11201201201201201201)
File "peproblem164.py", line 5, in func
sumlist.append(sum(int(m[i])+int(m[i+1])+int(m[i+2])))
TypeError: iteration over non-sequence'
That's because
int(m[i]) + int(m[i+1]) + int(m[i+2])
isn't a sequence. It's an int. I believe you mean:
sumlist.append(sum((int(m[i]), int(m[i+1]), int(m[i+2]))
this will work because
(int(m[i]), int(m[i+1]), int(m[i+2]))
is a sequence.
All in all, it would be easier to work with a list of integers, rather than a string, so it would make sense to convert m into ints first:
m = map(int, str(n))
and then use Python's slicing syntax to get the subsequence sums:
for i in range(18): #Leaving out the start argument is equivalent to range(0, 18)
sumlist.append(sum(m[i:i+3]))
and it would be even more pythonic to use a list comprehension instead (not to mention faster):
sumlist = [m[i:i+3] for i in range(18)] #same thing as the for loop
You really don't need the sum call. Replace
sumlist.append(sum(int(m[i])+int(m[i+1])+int(m[i+2])))
with
sumlist.append(int(m[i])+int(m[i+1])+int(m[i+2]))