I'm new to Python so my question may seem easy to some but then again I'm stuck on my own so I need your help! This is the code that i am having trouble with:
def identify_language(sequence, **common_words):
result = {}
for i in common_words:
result[i] = 0
for i in func_op(sequence.lower()):
for j in common_words:
if i in common_words[j]:
result[j] += 1
return sort(result[0][0])
...
dictionary = {'cro':list_cro, 'eng':list_cro}
language = identify_language('I had a little lamb. It was called Billy.', **dictionary)
I am trying to identify language based on samples which are in list_cro and list_eng (and hopefully others). I am getting KeyError: 0. Additionally, sort and func_op are working fine i tested then separately. What may be the problem?
Also, if i change order of arguments in function (putting list as a first argument and string as second) i am getting syntax error.
Thanks for listening!
At the end of the function, result should look like this: {'cro': X, 'eng': Y}, where X and Y are numbers. I don't know what your dictionaries are, so I can't guess what the numbers are. Evaluating result['eng'] will produce a number, as will result['cro'], but there is no 0 key in this dictionary.
Further, the second indexing operation will also give you issues. result['eng'][0] will give you an error because result['eng'] is a number, and you can't index into a number.
What do you expect the output of this function to look like? Where is sort defined and what is it supposed to do?
Related
I'm trying to make a challenge for one of the courses I'm following. I'm new to programming, but I'm eager to learn.
Can you tell me in detail why this error occurs to me and how do solve it.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
for i in default_names:
default_names[i]=default_names[i][0].upper()
i+=1
if i==len(default_names):
break
print default_names
the error: TypeError: list indices must be integers, not str
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
print default_names
What you are looking for is :
for i,s in enumerate(default_names):
or simple:
for i in range(len(default_names)):
The mistake you are doing is that when you say for i in default_names: notice that i value is a string, not int as you are trying to use.
for i in default_names:
print(i)
Will give :
OUT: Justin
john
Emilee
jim
Ron
Sandra
veronica
Wiskley
So the actual code should be, assuming you are trying to convert each string in list to Upper case :
for i in range(len(default_names)):
default_names[i]=default_names[i].upper()
EDIT : The OP wants only First char to be Upper case, and since string are immutable, change of code to :
for i in range(len(default_names)):
default_names[i]=default_names[i][0].upper() + default_names[i][1:]
As you can see in your error: TypeError: list indices must be integers, not str. It's because to access the elements of a list, you have to use the index, which is an integer. Basing on the structure of your code, you might have come from a different language. Python's for loop is different from the other languages. It doesn't increment the variable you made over the loop, but rather it iterates over the elements and passes the value to the variable. I think it would be more suitable to use a while loop with the code you made since you have initialized your i to 0. E.g.
default_names =['Justin', 'john','Emilee', 'jim','Ron','Sandra','veronica','Wiskley']
i=0
while i < len(default_names):
default_names[i]=default_names[i].upper() #removed the [0] here
i+=1
#removed the other codes here
print default_names
As you become better in python, you can find more efficient ways to do these kinds of things. The result you wanted could be simply made through
default_names = [name.upper() for name in default_names]
which simply iterates all of the names, makes it upper case and saves it back to default_names
Hi i have the following code:
m= list()
for i in range (1,6):
set = base.Getentity(constants.ABAQUS,"SET",i)
m.append(set)
print(set)
and my result is
<Entity:0*17a:id:1>
<Entity:0*14g:id:2>
<Entity:0*14f:id:3>
<Entity:0*14a:id:4>
None
None
Here i have four elemnts in my set named set. Even though my code is written in ansa python, my question is very General
I would like to write a code which goes through the set and prints the last elemnt in my case
'<Entity:0*17a:id:4>'.
and aslo i dont want to use the range function so pls help me with writing the code.
I suggest you look at Iterators, that will help you loop through the list
If you don't want to use the range function, you can use xrange. It returns an xrange object, which is kind of like an iterator and generates the numbers on demand.
You are getting None as the last two values because there are no 'set' with the id 5 and 6 in your model
Use a filter before appending to the list m
m= list()
for i in range (1,6)
set = base.Getentity(constants.ABAQUS,"SET",i)
if set!=None:
m.append(set)
Now you can just call m[-1] for the last entity
hope this helps
I have a function in python that checks if the value of listy_poo[0] is a certain value. If it is, I need to skip index 1 and get the value of index 2.
My code:
def find():
i = 0
for e in listy_poo:
if listy_poo[i] == 'value':
print(listy_poo[i+2])
i += 1
Clearly wrong, but is there something in python that accomplishes what I'm attempting?
UPDATE:
I thought the problem was the syntax of listy_poo[i+2] but looking over the history has shown that I actually didn't save my change from when I attempted listy_poo[i]+2, which is wrong. Thanks for your help anyway, folks.
Your code is close to working. If you change it to
def find(listy_poo, value_str):
for i, e in enumerate(listy_poo):
if e == value_str and i+2 < len(listy_poo):
print(listy_poo[i+2])
The enumerate() function returns a tuple of the index of the given item in the list, and the item itself. I also added a check (i+2 < len(listy_poo)) to make sure you don't get an IndexError.
Looking at your description, I'm not positive this is doing what you want.
If you ran find(['a','b','c','d'],'b') then the function would print out d. That is, whenever it finds a match for the value, it moves over two spots in the list, and prints that value. Is that what you are going for?
I'm currently learning python so I apologize in advance for the messiness of my code. My function is meant to take in a single string and add the string numbers together. i.e. A string argument of 123 will become 1 + 2 + 3 and return 6.
My issue is when I iterate through my list - python keeps indicating that the variable has been referenced before any value has been assigned. However when I print out the values being calculated they are correct. Even more confusing is that when I return them - they are incorrect. I can't seem to work out where I'm going wrong. Could anyone tell me what the issue may be?
Thank you!
listy = []
global total
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy.append(i)
print listy
#listy is printing [5,3,4]
for i in listy:
total += int(i)
return total
print digit_sum(x)
I'm not really sure what's going on in your code there, especially with the messed up indentation, but your problem is easily sovled:
sum(map(int, str(534)))
It makes the number a string, then converts each digit to an int with map, then just sums it all.
If your concern is only about summing a string of numbers, then list comprehension itself would do or as #Maltysen suggested you could use map
sum([int(x) for x in "534"])
pretty simple:
You can use a map or a list comprehension. They are pretty much equivalent. Other people gave an answer using map but I decided to use a list comprehension.
s = "1234567"
sum([int(character) for character in s])
I believe I have worked out what was wrong with my code. As I am still new to Python, I made some very novice mistakes such as not realizing declaring a variable outside the local function would result in the solution not being what I had expected.
Due to my returns being placed incorrectly as well as my listy [] variable being instantiated outside my function, instead of reading each number once, it would read it three times.
This has now been corrected in the code below.
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
total = 0
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy = []
listy.append(i)
# print listy
#listy is printing [5,3,4]
for i in listy:
print i
total+= int(i)
print total
break
return total
print digit_sum(111)
To learn python I am implementing Bulls and Cows. So I need to generate a 'random' number. I tried this:
possibilities = range(10)
number = "".join([str(possibilities.pop(random.choice(possibilities))) for i in range(4)])
Which I thought was a nice solution to the problem, but once in every couple of runs I get an IndexError on that line: IndexError: pop index out of range
So it looks like random.choice() gives me a non existent index. How come?
Or am I making a wrong assumption and is the problem something else entirely?
Come to think of it, I haven't got a clue how to debug a statement like this, any pointers on that?
Edit
My first solution was of the procedural kind:
for i in range(4):
idx = random.choice(possibilities)
number = number + str(possibilities[idx])
del possibilities[idx]
This code seems to do the exact same thing as the one-liner above, but has no problems whatsoever.
You aren't randomly choosing indices, you're choosing values from the list. What if you pick 9 after a lower number or two has been popped from the list?
Instead, use random.sample:
number = "".join(map(str, random.sample(range(10), 4)))