Changing a collection.Counter during enumeration? [duplicate] - python

This question already has answers here:
How does a for loop evaluate its argument
(3 answers)
Closed 6 years ago.
counter = Counter()
// fill data into counter
for a, b in counter.most_common():
if (b > 1):
counter[a] = np.log(b)
else:
counter[a] = -np.log((1 / (b+0.01)))
As I see, this is safe, based on my trial. No bad thing happens when I change the collection while I am enumerating it. In other languages, in each cycle of the for, the counter.most_common() value is evaluated.
Doesn't this happen in Python as well?

No, it doesn't. A more illustrative example:
def example():
print("Ping")
return [1,2,3,4]
for x in example():
print(x)
Output:
Ping
1
2
3
4

Related

How does python's built-in 'all' function work under the hood? Specifically, will it exit after finding the first false? [duplicate]

This question already has answers here:
Is the shortcircuit behaviour of Python's any/all explicit? [duplicate]
(4 answers)
Closed 9 months ago.
Will python's all function exit as soon as it finds a False in the iterable? Or will it continue checking the rest?
For example, if i is not divisible by 20, will the below code continue checking if it is divisible by 19 and 18 and so on?
def min_divisible(target_n):
'''
Returns the smallest number that is divisible by all integers between 1 and n
'''
i = target_n
while not all((i%j == 0) for j in range(target_n,2,-1)):
i+=target_n
return f'{i:,}'
print(min_divisible(20))
all will stop the iteration as soon as it encounters a "falsey" object. You can see this with a simple example:
def produce_numbers():
for k in range(10):
yield k
print(k)
all(k < 3 for k in produce_numbers())
This prints
0
1
2
This is spelled out in Python's documentation. It states that the following is a functionally equivalent definition of all:
def all(iterable):
for element in iterable:
if not element:
return False
return True

Is returning a list a good programming practice? [duplicate]

This question already has answers here:
What's the best way to return multiple values from a function? [duplicate]
(6 answers)
Alternatives for returning multiple values from a Python function [closed]
(14 answers)
Closed 2 years ago.
So i have a function that has to return 3 values, i haven't found a better way to do this other than returning a list. Is this code a good programming practice? And if not how to fix it.
Example function:
def func():
#code
return [a,b,c]
Main code:
#code
list = func()
k = list[0]
l = list[1]
m = list[2]
You can pack/unpack directly in python:
def func():
a = 1
b = 2
c = 3
return a, b, c
k, l, m = func()

Is it ok to put computation in the body of the for loop? [duplicate]

This question already has answers here:
How does a for loop evaluate its argument
(3 answers)
How many times does a for loop evaluate its expression list?
(1 answer)
Closed 3 years ago.
I want to make sure that d1-d2 does not recompute at each iteration at the first example. How can I check this?
>>> def f(d1: Counter, d2: Counter):
... for reason, count in (d1 - d2).items():
... print(reason, count)
...
>>> def f2(d1: Counter, d2: Counter):
... diff = (d1 - d2).items()
... for reason, count in diff:
... print(reason, count)
Any suggestions which way is more pythonic in terms of readability and performance?
The comments already explained that it does not matter. You also ask "how to check" that d1 - d2 is not evaluated twice, which is fairly simple by defining a function that prints something.
def foo():
print('foo')
return range(5)
for n in foo():
pass
This outputs foo once, which proves that foo() is called/evaluated exactly once (and not 5 times).

How to check multiple occurrences of a character in a string [duplicate]

This question already has an answer here:
Identifying straight, flush and other categories (from Poker) using Python
(1 answer)
Closed 3 years ago.
If there is a string = '99888' it should print 'True'. How can you check pairs and threes of a character in a string
I tried using the count function but it only identifies a pair
string = '99888'
for c in '123456789':
if string.count(c) == 2 and string.count(c) == 3 :
print('True')
Edit:
The string is a always 5 character string and if there is a pair and three of a kind it prints True
For example '89899' and '75757' print True. '98726' prints False
Use the Counter class from the collections module
from collections import Counter
def check(inputString):
x = Counter(inputString)
list_of_counts = [x[i] for i in x.elements()]
if (2 in list_of_counts) and (3 in list_of_counts):
return(True)
else:
return(False)
print(check("99888"))
print(check("999888"))

Initializing a pair of variables- what does the 1 mean? [duplicate]

This question already has answers here:
Unpacking, extended unpacking and nested extended unpacking
(4 answers)
Closed 3 years ago.
I'm trying to fundamentally understand while loops but don't understand assigning multiple variables on a single line of code.
total, x = 0, 1
What does the 1 mean? Where does the 1 belong? Plz help
total, x = 0, 1
it means :
total = 0
and
x = 1
You are basically assigning two variables simultaneously.
cat, dog = 'meow', 'woof'
is the same as:
cat = 'meow'
dog = 'woof'
You can use this method when you have a function that needs to return multiple variables.
def my_func(text):
return text, text.upper()
(original, edited) = my_func('hello')
print(original)
print(edited)
>>> hello
>>> HELLO

Categories

Resources