Python when generator 'yield' encounter 'random' [duplicate] - python

This question already has answers here:
Understanding generators in Python
(13 answers)
Closed 1 year ago.
Here i want to generate 5 dicts, where 'a' is index 'i', 'b' is a random int between 0 and 5. But result stuck at 'a'=0, it kept generate new c from random.randint(0,5) and 'i' remained the same. how to fix this? thx a lot
def wdg():
for i in range(5):
c = random.randint(0,5)
yield {'a':i,'b':c}
next(wdg())

Assign generator to a variable for example 'generator'. Then each time you call next(generator) one execution will occur, leading to increment i by one and generate random c:
generator = wdg()
print(next(generator))

Related

Python Combine two list [duplicate]

This question already has answers here:
python nested for loop when index of outer loop equals to length of inner loop you start again
(6 answers)
Closed 10 months ago.
I have
A = ['A','B','C','D','E','F','G','H','J']
B= ['a','b','c']
I want to combine the list that 'a' is combine with first three element of list A , 'b' with the next three and 'c' with the last three as shown below
C = ['Aa','Ba','Ca','Db','Eb','Fb','Gc','Hc','Jc,]
how can I go about it in python
As a list comprehension you could do this. Although I suspect there's a nicer way to do it.
[f"{capital}{B[i//3]}" for i,capital in enumerate(A)]
i will increment by 1 for each letter in A so we can do floor division by 3 to only increment it every 3 iterations of A giving us the correct index of B and just use an f-string to concaninate the strings although capital + B[i//3] works too.

Question caused by lambda expression in python? [duplicate]

This question already has answers here:
How does a lambda function refer to its parameters in python?
(4 answers)
Closed 1 year ago.
I wrote a Python code like:
fun_list = []
for i in range(10):
fun_list.append(lambda : f(i))
for j in range(10):
fun_list[j]()
I want it to output numbers from 0 to 9, but actually it outputs 9 for ten times!
I think the question is that the variable is be transported into function f only it was be called. Once it was be called it will globally find variable named 'i'.
How to modify the code so that it can output numbers from 0 to 9?
Your Code doesn't make sensefun_list[j]() how are you calling a List Element?
If You Want to append the numbers mentioned above into your array then Correct Code is:-
fun_list = []
for i in range(10): ### the range has to be from 0 to 10 that is [0,10)
fun_list.append(i) ### You dont need lambda function to append i
What This does is also if of No need because you first of all havent initialized what is f?... Is it a function?. You here are not appending the value but instead appending the called function statement. You dont need that. Just do it simply like above....:-
fun_list.append(lambda : f(i))

python "all" function making list empty [duplicate]

This question already has answers here:
Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?
(5 answers)
Closed 4 years ago.
I am new to python and was learning its builtins but function all()
is not behaving as expected i don't know why.Here is my code
n=map(int,input().strip().split())
print(all([j>0 for j in n]))
print(list(n)) #this line returning empty list
Here are my inputs:
1 2 3 4 5 -9
And my output:
False
Does function all changes the original map object(values)? but something like this is not mentioned in given function definition on the docs link.
Thanks in advance
Map returns a generator object which you exhausted in your all function. Therefore when you call list on n, since n is empty/exhausted, it returns an empty list.
To fix just make n a list in the first place.
n=list(map(int,input().strip().split()))
print(all([j>0 for j in n]))
print(n)

Printing out a list object created by a class [duplicate]

This question already has answers here:
Why is `print(object)` displaying `<__main__. object at 0x02C08790>`?
(5 answers)
Closed 4 years ago.
I am trying to create a program, which generates a list of all the numbers in the range of 0 to any number, in random order and with each number appearing only once (in order to program some sorting algorithms and test them on this list afterwards). I tried to create a List() class, which takes as argument the length of the list it is supposed to create:
from random import randint, shuffle
class List():
def __init__(self, length):
self.length = length
def create_list(self):
list_ = [i for i in range(self.length)]
testlist = List(10)
print(testlist)
Now the problem is, instead of a list, the output of this code is just
<__main__.List object at 0x02DD1FF0>
Is there anybody who can tell me why and how to correct this?
Note that I'm a beginner, I began learning python about 2 weeks ago and this is more or less my first attempt in OOP...
You should override the __str__() method of the object. This is what gets called when you print an object that isn't inherently "printable"

Recursion with one argument [duplicate]

This question already has answers here:
calculate length of list recursively [duplicate]
(2 answers)
Closed 7 years ago.
So, my goal is to count the number of arguments in a list using recursion. However, as I'm only to use one argument in the function call, I don't know how to solve it without a second "count" argument.
So far I have this, where I accumulate the 1's together.
def countElements(a):
if a==[]:
return []
else:
return [1] + countElements(a[1:])
def main():
a=[3,2,5,3]
print(countElements(a))
main()
Instead of returning an empty list in the base case, return 0, and instead of [1] + countElements(a[1:]), return 1 + countElements(a[1:]). That way, you're just keeping the running count instead of getting a list back.

Categories