We just learned for loops in class for about five minutes and we were already given a lab. I am trying but still not getting what I need to get. What I am trying to do is take a list of integers, and then only take the odd integers and add them up and then return them so if the list of integers was [3,2,4,7,2,4,1,3,2] the returned value would be 14
def f(ls):
ct=0
for x in (f(ls)):
if x%2==1:
ct+=x
return(ct)
print(f[2,5,4,6,7,8,2])
the error code reads
Traceback (most recent call last):
File "C:/Users/Ian/Documents/Python/Labs/lab8.py", line 10, in <module>
print(f[2,5,4,6,7,8,2])
TypeError: 'function' object is not subscriptable
Just a couple of minor mistakes:
def f(ls):
ct = 0
for x in ls:
# ^ Do not call the method, but just parse through the list
if x % 2 == 1:
ct += x
return(ct)
# ^ ^ parenthesis are not necessary
print(f([2,5,4,6,7,8,2]))
# ^ ^ Missing paranthesis
You're missing the parenthesis in the function call
print(f([2,5,4,6,7,8,2]))
rather than
print(f[2,5,4,6,7,8,2])
Related
Traceback (most recent call last):
File "main.py", line 17, in <module>
max_height = max(botmoves)
TypeError: '>' not supported between instances of 'tuple' and 'int'
This is the error I'm trying to find the biggest value in a list but it saying something about a ">" here is my code
from random import randint
points = 0
botmoves = [-1000]
for i in range(20):
guess = randint(0, 100)
print('Bot',"guessed the number was", guess)
print("The bot was",abs(guess-100),"off")
print("The bot gets",50 - abs(guess-100),"points")
points = 50 - abs(guess-100),"points"
botmoves.append(points)
max_height = max(botmoves) #this is where the error is
print(botmoves)
The max function needs to be able to compare values to each other, and it does that with the > operator. What the error is telling you is that there are different types of elements in the list, which cannot sensibly be compared to each other. In this case, an int and a tuple.
The reason for that is this line:
points = 50 - abs(guess-100),"points"
The ,"points" at the end makes points into a tuple, for example (37, "points"). The parentheses are optional in many cases.
Probably that's just a copy/paste mistake from the line above, and you didn't mean to put that there:
points = 50 - abs(guess-100)
I want to generate a random string of length n, on a given alphabet.
import random
alphabet = "ACTG"
n= 10
# print(''.join(random.choice(alphabet) for x in range(n)) ) # work fine
print(''.join(random.choice(alphabet, k=n))) # doesn't work
The error:
Traceback (most recent call last):
File "<input>", line 3, in <module>
TypeError: choice() got an unexpected keyword argument 'k'
The correct method is choices with s, so use random.choices.
The mistake come from the two function that have similar names. The first is random.choices with s, and the second one is random.choice without s.
import random
alphabet = "ACTG"
n= 10
# print(''.join(random.choice(alphabet, k=n))) # gives an error
print(''.join(random.choices(alphabet, k=n))) # the correct method, work fine
I have built a code for a codewars problem. I think it is correct but it shows me an error I don't understand.
Can you tell me what am I doing wrong?
import math
def waterbombs(fire, w):
s=""
countx=0
for i in fire:
if i=="x":
countx+=1
elif i=="Y":
countx=0
return sum(math.ceil(countx/w))
waterbombs("xxYxx", 3)
This is the error:
Traceback (most recent call last):
File "D:\Curso Python Pildorasinformaticas\Ejercicios Codewars\Aerial Firefighting.py", line 16, in <module>
waterbombs("xxYxx", 3)
File "D:\Curso Python Pildorasinformaticas\Ejercicios Codewars\Aerial Firefighting.py", line 13, in waterbombs
return sum(math.ceil(countx/w))
TypeError: 'int' object is not iterable
[Finished in 0.2s]
Why are you doing sum(math.ceil(countx/w)) ?
What is the objective of the sum method here, since there is only value returned by math.ceil ?
The sum would throw that error if you pass a single value to it. You're supposed to pass a list of values of the sum method.
For eg: sum(5) would give you the same error you see above, but sum([5]) would return you 5.
I have this for-loop:
for i in range(1000000000, 1000000030):
foo(i)
When I execute it this error is given:
Traceback (most recent call last):
File "/CENSORED/Activity.py", line 11, in <module>
for i in range(1000000000, 10000000030):
OverflowError: range() result has too many items.
As far as I know, this range-object should have exactly 30 elements...
Where is the problem?
Edit:
I have removed the extra zero, now I get this:
Traceback (most recent call last):
File "/CENSORED/Activity.py", line 12, in <module>
factorizeInefficient(i)
MemoryError
Edit 2:
def factorizeInefficient(n):
teiler = list()
for i in range(n):
if i != 0:
if (n%i)==0:
teiler.append(i)
print teiler
Just found the solution myself: There is a range(n) object in this as well and this causes the memory Error...
An extra question: How did you guys know this was python 2? (Btw you were right...)
Copy/pasting the range() part of your code:
>>> len(range(1000000000, 10000000030))
9000000030
So there are actually about 9 billion elements in the range. Your first argument is presumably missing a zero, or second argument has a zero too many ;-)
count your zeros once again ;) I'd say it's one too much.
Each line represents a single student and consists of a student number, a name, a section code and a midterm grade, all separated by whitespace.
The first parameter is already done and the file is open and
The second parameter is a section code
this is the link http://www.cdf.toronto.edu/~csc108h/fall/exercises/e3/grade_file.txt
My code:
def average_by_section(the_file, section_code):
'''(io.TextIOWrapper, str) -> float
Return the average midtermmark for all students in that section
'''
score = 0
n = 0
for element in the_file:
line = element.split()
if section_code == line[-2]:
mark = mark + float(line[-1])
n += 1
lecture_avg = mark / n
return lecture_avg
I'm getting an index out of range. Is this correct? Or am I just opening up the wrong file?
can someone test this code and download that file? I'm pretty sure it should work, but not for me.
Well, you can troubleshoot the index out of range error with a print line or print(line) to explore the number of items in "line" (i.e. the effect of split()). I'd suggest looking closer at your split() statement...
It looks like you are omitting parts of your code where you define some of those variables (section_code, mark, etc.), but adjusting for some of those things seems to work properly. Assuming that the error you got was IndexError: list index out of range, that happens when you try to access an element of a list by index where that index doesn't exist. For instance:
>>> l = ['one']
>>> l[0]
'one'
>>> l[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> l[-1]
'one'
>>> l[-2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Therefore in your code, you will get that error if line is ever fewer than two items. I would check and see what you are actually getting for line to make sure it is what you expect.