I am just learning python and was trying to define a function using a for loop.
The code is as follows -
def chk(hilist):
``` The function returns the output of the enumerate function as (x1,y1) (x2,y2)...
```
for item in enumerate(hilist):
return item
I ran the above function for the input 'string' as below -
abc = chk('string')
abc
The output came out as (0,s).
If I ran the regular for function and the output will be as follows -
(0, 's')
(1, 't')
(2, 'r')
(3, 'i')
(4, 'n')
(5, 'g')
Can someone please help me understand what I am doing wrong ?
Thanks in advance.
Return will break the function immediately.
So, you have to save the result in a list and return it:
def chk(hilist):
""" The function returns the output of the enumerate function as (x1,y1) (x2,y2)...
"""
ret_list=list()
for item in enumerate(hilist):
ret_list.append(item)
return ret_list
in Python (and in all programming languages), using the return keyword will get you out of the function, so I propose two solutions:
solution 1: store your tuples in a list and then return the list
itself
solution 2: replace return with yield (but if you want to print returned items convert it to a list ex: list(abc(some_arguments)))
I think the simplest solution would be to use print(item) if you wanna get all the enumerated values from 'string':
def chk(hilist):
for item in enumerate(hilist):
print(item)
This worked smoothly for me.
Related
em...I feel confused about this code, I am really new to coding, and wonder anyone can help:
def takeSecond(elem):# If I pass the argument as a list, why don't I need to specify it here?
return elem[1] # what return elem[1] means,does it return the y in (x,y)? but why!?
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond) # key = takeSecond what is this even mean lol?..
print('Sorted list:', random)
Let's say you have a list of items, which contains:
list = [a,b,c]
If you use the following piece of code:
def func():
return list[1]
You'd get "b" as output. The number "1" is not the first element, it's the second element. The counting in python starts at 0. So basically, if you want to access "a", you have to use:
def func():
return list[0]
Because 0 = a, 1 = b, 2 = c, and so on. If you change return elem[1] to return elem[0] you get the variable x.
Here your trying to sort based on second value in given list
takeSecond function is always returns the second value in the given element.
In random.sort() method calling with your passing key parameter as takeSecond function, which means sorting perform based on that element it happen. In our case it will return second element. So sorting is perform based on second element
And then printing the sorted list
I would like to check if one item is always followed with another within a list. I have come up with this really trite example... Let's say I would like to check if "a" is always followed by "b" in the following list:
list = ['x','y','z','a','b','2','3','5','2','1','5','fds','f','s','a','b']
Then, ideally, the function would return TRUE if every time we see an "a", it is directly followed by a "b". Can anyone help me with this? Maybe I am missing something really simple here.
all(a != 'a' or b == 'b' for a, b in zip(list[:-1], list[1:]))
You can use all with zip for an O(n) solution.
itertools.islice is used to avoid the expensive of making a new list. You can also wrap in a function as below.
from itertools import islice
def fun(lst, val1, val2):
return all(j==val2 for i, j in zip(lst, islice(lst, 1, None)) if i==val1)
lst = ['x','y','z','a','b','2','3','5','2','1','5','fds','f','s','a','b']
res = fun(lst, 'a', 'b')
print(res) # True
I have two variables:
myList = [(0, 't'), (1, 'r'), (2, '_')]
newList = []
I want to create a new list, which includes tuples that have alphabet character inside. The output should be:
newList = [(0, 't'), (1, 'r')]
My initial thought is:
for thing in myList:
if thing(1) in string.ascii_lowercase: #This line doesn't work.
newList.append(thing)
I have 2 questions:
Please help me with the broken code. Can you tell me the name of the error, for a beginner, it's even hard to know the right word to search google.
Please give advice on naming things. Like in this example, how would you name thing?
You need to change:
if thing(1) in string.ascii_lowercase:
to:
if thing[1] in string.ascii_lowercase:
Also make sure you have importedstring.
You can rename thing to list_tuple or my_list_object for example. You will get good at naming eventually.
The "Pythonic" way to accomplish your goal is as follows:
import string
newList = filter(lambda x: type(x) is tuple and x[1] in string.ascii_lowercase, myList)
Explanation:
import string: importing the string module to obtain a list of all alphabet
filter(condition, iterable): an extremely useful, builtin, function of Python which allows you to filter out unwanted elements from a list (or any other iterable for that matter)
lambda x: an (usually simple) anonymous function defined at runtime which operates on a runtime variable x
type(x) is tuple and x[1] in string.ascii_lowercase: when operating on each element x in the iterable passed to filter, the lambda function first verifies that the element is indeed a tuple, and if so, checks if the first element is in the lowercased alphabet
Hope this helps
primes = [2,3,5,7..] (prime numbers)
map(lambda x:print(x),primes)
It does not print anything.
Why is that?
I've tried
sys.stdout.write(x)
too, but doesn't work either.
Since lambda x: print(x) is a syntax error in Python < 3, I'm assuming Python 3. That means map returns a generator, meaning to get map to actually call the function on every element of a list, you need to iterate through the resultant generator.
Fortunately, this can be done easily:
list(map(lambda x:print(x),primes))
Oh, and you can get rid of the lambda too, if you like:
list(map(print,primes))
But, at that point you are better off with letting print handle it:
print(*primes, sep='\n')
NOTE: I said earlier that '\n'.join would be a good idea. That is only true for a list of str's.
This works for me:
>>> from __future__ import print_function
>>> map(lambda x: print(x), primes)
2
3
5
7
17: [None, None, None, None]
Are you using Python 2.x where print is a statement, not a function?
Alternatively, you can unpack it by putting * before map(...) like the following
[*map(...)]
or
{*map(...)}
Choose the output you desire, a list or a dictionary.
Another reason why you could be seeing this is that you're not evaluating the results of the map function. It returns a generator (an iterable) that evaluates your function lazily and not an actual list.
primes = [2,3,5,7]
map(print, primes) # no output, because it returns a generator
primes = [2,3,5,7]
for i in map(print, primes):
pass # prints 2,3,5,7
Alternately, you can do list(map(print, primes)) which will also force the generator to be evaluated and call the print function on each member of your list.
I have a tuple and would like to reverse it in Python.
The tuple looks like this : (2, (4, (1, (10, None)))).
I tried reversing in Python by:
a = (2, (4, (1, (10, None))))
b = reversed(a)
It returns me this:
<reversed object at 0x02C73270>
How do I get the reverse of a? Or must I write a function to do this?
The result should look like this:
((((None, 10), 1), 4), 2)
def my_reverser(x):
try:
x_ = x[::-1]
except TypeError:
return x
else:
return x if len(x) == 1 else tuple(my_reverser(e) for e in x_)
Try this deep-reverse function:
def deep_reverse(t):
return tuple(deep_reverse(x) if isinstance(x, tuple) else x
for x in reversed(t))
This will handle arbitrarily nested tuples, not just two-tuples.
As explained in the documentation, the reversed function returns an iterator (hence the <reversed at ...>). If you want to get a list or a tuple out of it, just use list(reversed(...)) or tuple(reversed(...)).
However, it's only part of our problem: you'll be reversing the initial object (2, (...)) as (...,2), while the ... stays the same. You have to implement a recursive reverse: if one element of your input tuple is an iterable, you need to reverse it to.
It does not make sense to do this with reversed, sorry. But a simple recursive function would return what you want:
def reversedLinkedTuple(t):
if t is None:
return t
a, b = t
return reversedLinkedTuple(b), a
reversed is usable only on reversible iterable objects like lists, tuples and the like. What you are using (a linked list) isn't iterable in the sense of the Python built-in iter.
You could write a wrapping class for your linked list which implements this and then offers a reverse iterator, but I think that would be overkill and would not really suit your needs.
def reverse(x):
while x >= 0:
print(x)
x = x = 1
reverse(x)