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)
Related
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.
A very simple thing - I downloaded python 3.8 and installed numpy. Upon making a very basic program that uses a numpy function, I get an error. I captured all the info that I think is relevant for now:
Traceback (most recent call last):
File "C:/Python/numpytest.py", line 6, in <module>
a=sigmoid(2)
File "C:/Python/numpytest.py", line 4, in sigmoid
return 1/(1+exp(-x))
NameError: name 'exp' is not defined
I'm guessing it isn't even importing numpy but no idea why.
Use np.exp(x) to access Numpy's exp() function.
Otherwise, import Numpy as:
from numpy import *
to use exp() without any prefix.
For example,
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
a=sigmoid(2)
print(a)
You need to call the np class then the exp function
Also, it is better to copy the text rather than take a picture of it.
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).
I have installed numpy but when I import it, it doesn't work.
from numpy import *
arr=array([1,2,3,4])
print(arr)
Result:
C:\Users\YUVRAJ\PycharmProjects\mycode2\venv\Scripts\python.exe C:/Users/YUVRAJ/PycharmProjects/mycode2/numpy.py
Traceback (most recent call last):
File "C:/Users/YUVRAJ/PycharmProjects/mycode2/numpy.py", line 1, in <module>
from numpy import *
File "C:\Users\YUVRAJ\PycharmProjects\mycode2\numpy.py", line 2, in <module>
x=array([1,2,3,4])
NameError: name 'array' is not defined
Process finished with exit code 1
The problem is you named your script as numpy.py, which is a conflict with the module numpy that you need to use. Just rename your script to something else and will be fine.
Instead of using from numpy import *
Try using this:
import numpy
from numpy import array
And then add your code:
arr=array([1,2,3,4])
print(arr)
EDIT: Even though this is the accepted answer, this may not work under all circumstances. If this doesn't work, see adrtam's answer.
I have Python 3.3.3 and SymPy 0.7.4.1, both in x64 version and installed locally on my computer. I am using PSPad as a configured editor for Python scripting.
When using imports from library sympy in a module which should solve a set of three linear equations:
from sympy import Matrix, solve_linear_system
from sympy.abc import x, y, z
def main():
system = Matrix (((3,2,-1,1) ,(2,-2,4,-2),(-1,0.5,-1,0)))
print(solve_linear_system(system, x, y,z))
if __name__ == "__main__":
main()
The editor PSPad console output returns the following:
traceback (most recent call last): File "C:\Users\GOODLU~1\AppData\Local\Temp\PSpad\securesafety_DISK_5GB\Programmation\linear system solve SYMPY.py", line 1, in <module>
from sympy import Matrix,solve_linear_system File "C:\Users\GOODLU~1\AppData\Local\Temp\PSpad\securesafety_DISK_5GB\Programmation\sympy.py", line 2, in <module>
from sympy import var,Eq,solve ImportError: cannot import name var
Process completed, Exit Code 1.
Execution time: 00:00.134
Actually, I am wondering myself heavily about those issues:
Why, when typing the same thing, without an object def main(), and entered line by line in IDLE, everything is solved correctly, as: {x: 1.00000000000000, y: -2.00000000000000, z: -2.00000000000000}
Why, my PSPad file with object, having the same computation lines, doesn't work and returns errors?
In fact, I would like to use SymPy in normal python code and get computed results in a list or printed in console( .. as in IDLE). Just in order to avoid some annoying line-to-line IDLE manipulations, what should my code file look like?
The problem seems to be that you have created a file named sympy.py, which has the same name as the sympy module.
Hence, in the from sympy import ... statement, your sympy.py is acting as the sympy module.
Try renaming the file to something else, like sympy_programming_test.py and let know if it works.