Random Module has not attribute 'choices' - python

I am using Sublime Text3. I am encountering a problem with the choices attribute with the random module. I do not have the same name in any path or directory. The other attributes of random work just fine.
import random
import string
letters = string.ascii_lowercase
print(letters)
gen = random.choices(letters, k=16)
print(gen)
Here is the error code:
abcdefghijklmnopqrstuvwxyz
Traceback (most recent call last):
File "/home/anon/.config/sublime-text-3/Packages/User/test.py", line 6, in <module>
gen = random.choices(letters)
AttributeError: 'module' object has no attribute 'choices'
What are the common causes of this problem?

There's no random.choices in Python 2. You can use random.sample in Python 2.
gen = random.sample(letters, k=16)
random.choices is included in Python 3

It would seem you are using a version of Python that is older than 3.6 which is when random.choices was introduced. You can see it listed at the bottom of this function description here
You can verify your version by running
import sys
sys.version

I encountered the same error when I used Python 2.7.
As a workaround, I simply used random.choice instead of random.choices, in a way as
foo = [random.choice(my_list) for _ in range(50)]
Although we do not have random.choices in Python 2.7, we have random.choice (the former is multiple choices with duplicates, while the latter single choice).

Related

MicroPython application throws AttributeError for very basic use of re.split without a duplicate "re.py" file present

I don't seem to understand why my rather generic use of the split function from the re library is failing:
from machine import Pin, SPI, UART
from array import array
import sys, re, time, math, framebuf
sys.path.append("C:/Source/Pico/SSD1322_SPI_4W")
print(sys.path)
import ssd1322
print("Test print")
s1="123\t123\t123"
s2 = re.split(r'\t', s1)
print(s2)
The output produced is as follows:
MicroPython v1.19.1 on 2022-06-18; Raspberry Pi Pico with RP2040
Type "help()" for more information.
%Run -c $EDITOR_CONTENT ['', '.frozen', '/lib', 'C:/Source/Pico/SSD1322_SPI_4W']
Test print
Traceback (most recent call last):
File "", line 67, in
AttributeError: 'module' object has no attribute 'split'
This script is developed for MicroPython v1.19.1 (Thonny 3.3.13 running Python 3.7.9) on a Win7 machine used to connect and deploy to a Raspberry Pi Pico (RP2040). I pared down the source to the least amount of code that would still reproduce the issue, but felt I ought to leave my imports incase the issue could be a library redundantly calling another library. I am fairly new to both Python and the Pico, so I'm probably just being ignorant of something basic and essential here. Someone in the comments here asked about creating another module/file "re.py" that would cause the script to attempt to use this instead, but I don't see such a file in the program directory.
Additionally, I have tried alternatives to the split line:
s2 = re.split(r"[^a-zA-Z0-9_]+", s1)
s2 = re.split(r"[\W]+", s1)
...but both provide the same result.
Thanks
In Micropython, you need to compile the matching pattern and then call the split method on the returned regex object.
import re
s1="123\t123\t123"
pattern = re.compile(r'\t')
s2 = pattern.split(s1)

ERROR : When trying deployment of model in ML I get-'dict' object is not callable

I have used the below code for my python streamlit deployment of ML Model.
import streamlit as st
import pickle
import numpy as np
import pandas as pd
similarity=pickle.load(open(r'C:\Users\nikso\OneDrive\Desktop\mlproject\similarity.pkl','rb'),buffers=None)
list=pickle.load(open(r'C:\Users\nikso\OneDrive\Desktop\mlproject\movies_dict.pkl','rb'),buffers=None)
movies=pd.DataFrame.from_dict(list)
def recomm(movie):
mov_index=movies[movies['title']==movie].index[0]
sim=similarity[mov_index]
movlist=sorted(list(enumerate(sim)),reverse=True,key=lambda x:x[1])[1:6]
rec_movie=[]
for i in movlist:
# print(i[0])
rec_movie.append(movies.iloc[i[0]]['title'])
return rec_movie
st.title('Movie Recommender System')
selected_movie_name = st.selectbox(
'How would you like to be contacted?',
movies['title'].values)
if st.button('Recommend'):
recom=recomm(selected_movie_name)
# recom=np.array(recom)
for i in recom:
st.write(i)
On colab the code is working fine but on vscode it was showing this error.
File "C:\Users\anaconda3\envs\Streamlit\lib\site-packages\streamlit\scriptrunner\script_runner.py", line 554, in _run_script
exec(code, module.__dict__)
File "C:\Users\OneDrive\Desktop\mlproject\app.py", line 30, in <module>
recom=recomm(selected_movie_name)
File "C:\Users\OneDrive\Desktop\mlproject\app.py", line 15, in recomm
movlist=sorted(list(enumerate(sim)),reverse=True,key=lambda x:x[1])[1:6]
Now I had to use different IDEs for deployement. But when I removed the keyword 'list' in the given line 15 it worked fine. What can be the reason behind it? I am ca begineer and really curious about it. Thank you.
But when I removed the keyword 'list' in the given line 15 it worked fine. What can be the reason behind it?
TL;DR: sorted accepts iterables, and enumerate is already an iterable
Long answer:
When you define list as
list=pickle.load(open(r'C:\Users\nikso\OneDrive\Desktop\mlproject\movies_dict.pkl','rb'),buffers=None)
you're overriding Python's built-in list type. Python lets you do this without issuing any warnings, but the result is that, in your script, list now represents a dictionary object. The result of this is that when you call list(enumerate(sim)) later on, you're treating your dictionary object as a callable, which it is not.
The solution? Avoid overriding Python built-ins whenever you can.
import streamlit as st
import pickle
import numpy as np
import pandas as pd
similarity=pickle.load(open(r'C:\Users\nikso\OneDrive\Desktop\mlproject\similarity.pkl','rb'),buffers=None)
movies_dict=pickle.load(open(r'C:\Users\nikso\OneDrive\Desktop\mlproject\movies_dict.pkl','rb'),buffers=None)
movies=pd.DataFrame.from_dict(movies_dict)
def recomm(movie):
mov_index=movies[movies['title']==movie].index[0]
sim=similarity[mov_index]
movlist=sorted(list(enumerate(sim)),reverse=True,key=lambda x:x[1])[1:6]
rec_movie=[]
for i in movlist:
# print(i[0])
rec_movie.append(movies.iloc[i[0]]['title'])
return rec_movie
st.title('Movie Recommender System')
selected_movie_name = st.selectbox(
'How would you like to be contacted?',
movies['title'].values)
if st.button('Recommend'):
recom=recomm(selected_movie_name)
# recom=np.array(recom)
for i in recom:
st.write(i)
To answer specifically why removing "list" on line 15 seemed to fix the issue, though: sorted accepts iterables, and enumerate is already an iterable. All list is doing on line 15 is gathering the results of enumerate before passing them into sorted. But the fundamental reason why removing list fixed things is because you're overriding Python's built-in, which you probably want to avoid doing.

python3.6 ImportError: cannot import name 'reduce'

from functools import reduce
I'm using python 3.6.2, and this is the only code that shows the following error:
Traceback (most recent call last):
File "D:\Pythons\oop.py", line 50, in <module>
from functools import reduce
ImportError: cannot import name 'reduce'
Process returned 1 (0x1) execution time : 0.145 s
I will find this problem because I made a mistake in another code,
from enum import Enum
It reported the error:
Traceback (most recent call last):
File "D:\Pythons\oop.py", line 50, in <module>
from enum import Enum
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\enum.py", line 3, in <module>
from functools import reduce ImportError: cannot import name 'reduce'
So I just looked at the enum. Py source,Found in line 3
from functools import reduce
Ladies and gentlemen, in centos7.2 installed python3.6.2 is completely out of any problems, but under the Windows 10 professional version installed, will appear these problems above, seems I installed out of the question, however, many times I've uninstalled, installed the many times repeatedly, still won't do, don't know without those documents, who can tell me how to through the command line in the Windows environment to install it?
Python 3.6 should have reduce in functools. To debug your problem, try this:
import functools
for obj in dir(functools):
print(obj)
I would expect an output similar to (tried it here: https://www.python.org/shell/):
MappingProxyType
RLock
WRAPPER_ASSIGNMENTS
WRAPPER_UPDATES
WeakKeyDictionary
_CacheInfo
_HashedSeq
__all__
__builtins__
__cached__
__doc__
__file__
__loader__
recursive_repr
__name__
__package__
__spec__
_c3_merge
_c3_mro
_compose_mro
_convert
_find_impl
_ge_from_gt
_ge_from_le
_ge_from_lt
_gt_from_ge
_gt_from_le
_gt_from_lt
_le_from_ge
_le_from_gt
_le_from_lt
_lru_cache_wrapper
_lt_from_ge
_lt_from_gt
_lt_from_le
_make_key
cmp_to_key
get_cache_token
lru_cache
namedtuple
partial
partialmethod
recursive_repr
reduce
singledispatch
total_ordering
update_wrapper
wraps
My guess is more than reduce will be missing. In any case, it looks like an Uninstall than Reinstall is in order. You may have accidently edited the file or corrupted it in some way. Sometimes an IDE could take you to that function and it would be easy to edit it accidentally.
Don't take care of those errors. Just try to use functools in your code :
import functools
# Create a list of strings: stark
stark = ['robb', 'sansa', 'arya', 'eddard', 'jon']
# Use reduce() to apply a lambda function over stark: result
result = functools.reduce((lambda item1,item2:item1 + item2), stark)
or like that :
# Import reduce from functools
from functools import reduce
# Create a list of strings: stark
stark = ['robb', 'sansa', 'arya', 'eddard', 'jon']
# Use reduce() to apply a lambda function over stark: result
result = reduce((lambda item1,item2:item1 + item2), stark)

Why is there different behaviour from getpwuid and getgrgid?

In Python 2.7, 3.4 and 3.5, grp.getgrgid is capable of accepting a string:
from grp import getgrgid
print(getgrgid('0'))
However, pwd.getpwuid can't do the same:
from pwd import getpwuid
print(getpwuid('0'))
Traceback (most recent call last):
File "getpwuid_test.py", line 2, in <module>
print(getpwuid('0'))
TypeError: an integer is required
This is because inside Modules/pwdmodule.c, getpwuid uses PyNumber_ParseTuple with a converter that uses PyNumber_Index to get a Python integer, and that raises an exception on failure.
However, in Modules/grpmodule.c, grp_getgrgid uses PyNumber_Long (Or PyNumber_Int for an old enough Python) as a conversion first, and as the documentation says at https://docs.python.org/3/c-api/number.html, this is the equivalent of running int(o), which can convert a string to an integer. Only then is it given to PyNumber_Index, by way of a helper function _Py_Gid_Converter
What is the reason for this difference? Is it a deliberate choice based on some history?
The behaviour of getgrgid seems more helpful, and it's odd that it doesn't apply to both functions. Is this undesirable behaviour in getgrgid or getpwuid?
The short answer is because humans are fallible and mistakes happen. Some are doozies and get noticed quickly, others are minor and can go years without detection.
Thank you for helping make Python better!

comtypes: in call_with_inout, ctypes TypeError: 'c_double' object is not iterable

Im working with Agilent IVI drivers in Python 2.7.9 and can't seem to get 'proven' code to work on a particular Windows 7 machine. It executes successfully on other machines.
While this issue seems rather limited to one instrument, it appears to be a broader Python issue, so I turn to Stack Overflow for help. Any help or insight would be great.
The following code
# Import the TLB
from comtypes.client import GetModule, CreateObject
GetModule('AgInfiniium.dll')
# Pull in the coefficients and classes, we'll need those
from comtypes.gen.AgilentInfiniiumLib import *
# Instantiate the driver
OScope = CreateObject('AgilentInfiniium.AgilentInfiniium')
# Make constants of our settings
Address = "TCPIP0::10.254.0.222::INSTR"
resetOScope = False
# Open a connection to the scope
OScope.Initialize(Address,False,resetOScope,'')
# Make a measurement
print OScope.Measurements.Item("Channel1").ReadWaveformMeasurement(
MeasFunction=AgilentInfiniiumMeasurementAmplitude, MaxTime=10)
yields the following error:
Traceback (most recent call last):
File "P:\Aperture\Validation\WMI_BGA_Board\TestMatrixCode\scopeTest2.py", line 29, in <module>
print OScope.Measurements.Item("Channel1").ReadWaveformMeasurement(MeasFunction=AgilentInfiniiumMeasurementAmplitude ,MaxTime=10)
File "C:\Python27\lib\site-packages\comtypes-1.1.0-py2.7.egg\comtypes\__init__.py", line 656, in call_with_inout
rescode = list(rescode)
TypeError: 'c_double' object is not iterable
In my limited debugging attempts, I have seen that this call_with_inout
function tries to convert my Python arguments into arguments for the following C++ function:
public void ReadWaveformMeasurement(
AgilentInfiniiumMeasurementEnum MeasFunction,
AgilentInfiniiumTimeOutEnum MaxTime,
ref double pMeasurement)
It's creating some kind of variable for the pMeasurement pointer that ends up being type c_double, and then complains that it's not iterable.
At this point, this seems like it's local to this machine. I've gone to the extent of uninstalling Python, reinstalling the Agilent driver, and trying two versions of comtypes (1.1.0 and 1.1.1). Yet the problem persists. Any ideas? Thanks.

Categories