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?
Related
l = [1,2,4]
for i in range(3):
a = l[i]
im tryihng to do that above but it isn't working and it says
'builtin_function_or_method' object cannot be interpreted as an integer. can anyone say why this is and tell me how to fix this
edit:There was something earlier in the code before this and it was because i was doing .lower and not .lower() sorry guys
Let's explain what your code does before solving it. Edit available at the bottom of the answer
for i in range(3):
a = l[i]
What this does is creates a "range" of numbers from 0 to 2, however its supposed to go from 1 (or 0) to 3. Why? Computers have been trained to start counting from 0 instead of 1 like a normal human and subsequently they are 1 less. (This is a simplified one, there's a longer one that you'll learn over time)
Now your 2nd line of code assigns the variable a the value of one of the items in the list l. Let's look at what value 'a' would be assigned during this time
1 (1st item)
2 (2nd item)
IndexError: Out of range error (there is no 3rd item)
So how do you solve this? One way is to add more items to your list l.
So let's then add 2 more items into l (3 and 4)
This is our variable l now
l = [1, 2, 3, 4]
Here's our output now
1 (1st item)
2 (2nd item)
3 (3rd item)
As you noticed, it skips the 4th item since we specified to only iterate over 3 items in the list. If you wanted to "iterate over a list" look no further!.
Observe
for i in l:
print(i)
This creates a for loop that goes over each item in the list l one by one from start to finish that allows you to see the current item in the variable i! In our code, it simply prints the variable i each time the for loop goes to the next item in the list.
1
2
3
4
And simply stops once it reaches the end!
Don't worry, we've all been there while learning code :)
UPDATE: Based on what you were saying, I'm assuming if you wanted to assign the variable a the 2nd place in the list 'l' you would use
a = l[1]
Yes to get the 2nd place you need to type 1. The same goes for accessing the 1st item, you change the l[1] with l[0]. This is because computers count from 0 instead of human's traditionally counting from 1
the code you wrote isn't even syntactically correct.
l = [1,2]
for i in range(len(l)):
# you had no colon, so the first error you should have gotten is a syntax error.
# the second error you would have gotten is a value error, because you try to set 'a' to values
# that don't exist. a more dynamic way to do it anyways is to cycle through the
# length of the list.
a = l[i]
im not sure why you want to do this, as it will result in a = 2. staying true to your question, the only reasonable way to do what you're asking is something as easy as this.
a = l[2] # or whatever index you're trying to get
you're method, even if it compiled correctly, would not have accomplished what you say you want.
as mentioned by 'meh' and 'shriakhilc', keep in mind that indexing starts at 0, so the list l would only have indexes of 0 and 1.
Working with a question right now where it asks me to generate a new list from a given list who's length will be 1 less than that of the originals.
I think I know what concepts need to be used but I can't figure out how to put it together to work.
I have this so far but it adds up the numbers in the list instead of just listing them and taking 1 element away from the given list.
def forward_difference(elems):
values = []
total = 0
for x in elems:
total += x
values = values[:-1]
values.append(total)
return values
print (forward_difference([1,2,3,4]))
I know that in order to get shorten a list or take an element away, something like this can be done:
values = [1,2,3]
values = values[:-1]
print (values)
Output:
[1,2]
Still new to python and trying to grasp the concepts better, any help would be greatly appreciated!
The output that I expected was [1,2,3] but instead I keep getting [1,3,6,10]
You don't need to use a loop. The second code you posted does what you ask, the only thing left is to put it inside a function:
def forward_difference(elems):
return elems[:-1]
print(forward_difference([1,2,3,4]))
Output:
[1,2,3]
I don't know how to ask this so I'm going to explain what I'm doing instead. I'm trying to search a list of lists with only 2 values. The first value I don't care about the second how ever I need to check and if it exsists I need the first value. Example
list = [[1,'text1'],[1,'text2'],[3,'text3'],[2,'text4']]
so basically I need to know if there is a character like % or ! that when used in find basically means any value. Link find(!,'text2') would get me the value of 1. (i know that wouldn't work like that). Ik I have the option of searching just the second value in lists but that's unecessary code if there is a special character as such.
There is no specific character or value for that, but you can either create your own sentinel object or you can use None for this. Just make sure to use is to detect it within your code.
# fmod.py
Any = object()
def find(first=Any, second=Any):
if first is Any:
...
...
import fmod
fmod.find(None, 'text2')
fmod.find(fmod.Any, 'text2')
You can do this with a list comprehension:
def findit(word, lst):
return [el[0] for el in lst if el[1] == word][0]
Try None value.
You can read more information about it here: Python 3 Constrants
When you say "the second how ever I need to check and if it exists I need the first value", I'm thinking you need to check if the second value is a) there (if the list has two elements) and b) of nonzero length (assuming they'll always be strings). This leads me to:
list_to_search = [[1,'text1'],[1,'text2'],[3,'text3'],[2,'text4'], [3], [4, '']]
firsts_with_seconds = [item[0] for item in list_to_search
if len(item) > 0 and len(item[1]) > 0]
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?
New to Python and trying to understand recursion. I'm trying to make a program that prints out the number of times string 'key' is found in string 'target' using a recursive function, as in Problem 1 of the MIT intro course problem set. I'm having a problem trying to figure out how the function will run. I've read the documentation and some tutorials on it, but does anyone have any tips on how to better comprehend recursion to help me fix this code?
from string import *
def countR(target,key):
numb = 0
if target.find(key) == -1:
print numb
else:
numb +=1
return countR(target[find(target,key):],key)
countR('ajdkhkfjsfkajslfajlfjsaiflaskfal','a')
By recursion you want to split the problem into smaller sub-problems that you can solve independently and then combine their solution together to get the final solution.
In your case you can split the task in two parts: Checking where (if) first occurence of key exists and then counting recursively for the rest.
Is there a key in there:
- No: Return 0.
- Yes: Remove key and say that the number of keys is 1 + number of key in the rest
In Code:
def countR(target,key):
if target.find(key) == -1:
return 0
else:
return 1+ countR(target[target.find(key)+len(key):],key)
Edit:
The following code then prints the desired result:
print(countR('ajdkhkfjsfkajslfajlfjsaiflaskfal','a'))
This is not how recursion works. numb is useless - every time you enter the recursion, numb is created again as 0, so it can only be 0 or 1 - never the actual result you seek.
Recursion works by finding the answer the a smaller problem, and using it to solve the big problem. In this case, you need to find the number of appearances of the key in a string that does not contain the first appearance, and add 1 to it.
Also, you need to actually advance the slice so the string you just found won't appear again.
from string import *
def countR(target,key):
if target.find(key) == -1:
return 0
else:
return 1+countR(target[target.find(key)+len(key):],key)
print(countR('ajdkhkfjsfkajslfajlfjsaiflaskfal','a'))
Most recursive functions that I've seen make a point of returning an interesting value upon which higher frames build. Your function doesn't do that, which is probably why it's confusing you. Here's a recursive function that gives you the factorial of an integer:
def factorial(n):
"""return the factorial of any positive integer n"""
if n > 1:
return n * factorial(n - 1)
else:
return 1 # Cheating a little bit by ignoring illegal values of n
The above function demonstrates what I'd call the "normal" kind of recursion – the value returned by inner frames is operated upon by outer frames.
Your function is a little unusual in that it:
Doesn't always return a value.
Outer frames don't do anything with the returned value of inner frames.
Let's see if we can refactor it to follow a more conventional recursion pattern. (Written as spoiler syntax so you can see if you can get it on your own, first):
def countR(target,key):
idx = target.find(key)`
if idx > -1:
return 1 + countR(target[idx + 1:], key)
else:
return 0
Here, countR adds 1 each time it finds a target, and then recurs upon the remainder of the string. If it doesn't find a match it still returns a value, but it does two critical things:
When added to outer frames, doesn't change the value.
Doesn't recur any further.
(OK, so the critical things are things it doesn't do. You get the picture.)
Meta/Edit: Despite this meta article it's apparently not possible to actually properly format code in spoiler text. So I'll leave it unformatted until that feature is fixed, or forever, whichever comes first.
If key is not found in target, print numb, else create a new string that starts after the the found occurrence (so cut away the beginning) and continue the search from there.