I wrote some code (named exercise 2) where I define a function (named is_divisible) and it has worked perfectly.
Afterwards to learn how to import functions, I wrote the same code but without the defined function, and created a second module (named is_divisible). But whenever I import this module into the original "exercise 2" I get
No module named 'is_divisible'
I have checked that both python files are in the same folder, the name of the file is correct, and I know the code is well written because it has worked before and it is from a lecturer's of mine. I have also attempted to name the module and the function differently and to instead write:
from divis import is_divisible
but this was also unsuccessful.
Where am I going wrong? I will leave the code below:
import random
import math
import numpy as np
random_list=[]
for i in range (0,5):
r=random.randint(0,10)
random_list.append(r)
print(random_list) #five numbers from 0 to 10 are chosen and appended to a list
new_result=[print('right' for x in random_list if round(np.cosh(x)**2 - np.sinh(x)**2,2) == 1]
#checking the numbers following a maths rule
import is_divisible #trying to import the function is_divisible
divisor=3
idx = is_divisible(random_list, divisor)
for i in idx:
print(f'Value {random_list[i]} (at index {i}) is divisible by {divisor}')
the code for the function is_divisible is:
def is_divisible(x, n):
""" Find the indices of x where the element is exactly divisible by n.
Arguments:
x - list of numbers to test
n - single divisor
Returns a list of the indices of x for which the value of the element is
divisible by n (to a precision of 1e-6 in the case of floats).
Example:
>>> is_divisible([3, 1, 3.1415, 6, 7.5], 3)
[0, 3]
"""
r = []
small = 1e-6
for i, m in enumerate(x):
if m % n < small:
r.append(i)
return r
I know this question has been answered multiple times, but none of the answers seem to work for me or maybe I am not doing it correctly.
Generally, when you type import <Module> the module is the name of the file. So, if you had the function is_divisible inside a Python file named a.py, then to import it you will write from a import is_divisible. If instead, you would like to import the whole file, then you'd write import a.py, then to use the function you would use a.is_divisible(random_list, divisor).
You should also make sure that both files are in the same folder.
Related
I am attempting to use timeit to keep track of how long a sorting algorithm takes to finish. However, it seems I can't even find an answer online how to exactly run timeit with functions that were originally written in another module. I've tried various setups and string inputs but am finding myself lost on this.
I tried using "t = timeit.Timer('sort.bubble(temp_array)')," but printing out the timer objects only gives me the memory addresses and cannot be converted to an integer...
In this case, I am calling bubble sort from another module.
#This section is on a timetests.py file
import random
import sort
import timeit
test_array1 = [random.randint(0, 500) for i in range(10)]
arrays_to_sort = [test_array1]
bubble_times = []
for a in range(len(arrays_to_sort)):
temp_array = arrays_to_sort[a]
t = timeit(sort.bubble(temp_array))
bubble_times.append(t)
**t = timeit(sort.bubble(temp_array))** #code is definitely not correct here
#This file is on sort.py
def bubble(list):
for current_pass in range(len(list) - 1, 0, -1):
for element in range(current_pass):
#Swap the element if the current one is smaller than
#next one
if list[element] > list[element + 1]:
temp = list[element]
list[element] = list[element + 1]
list[element + 1] = temp
return list
You need to function bubble and variable temp_array in the local environment.
Try:
t = timeit.timeit("bubble(temp_array)", setup = "from sort import bubble; from __main__ import temp_array"),
bubble_times.append(t)
Explanation:
So we use bubble() since that's the way to access an imported function
you would use sort.bubble() if you had imported the sort module rather than just a function from the module
We have to also bring in temp_array (assuming we are running timetests.py as the main module)
Using lambda function
Another option is use lambda to create a zero argument function which we pass to timeit. Note: checkout how to pass parameters of a function when using timeit.Timer()
t = timeit.timeit(lambda: sort.bubble(temp_array))
I need to solve for a list (because there are two of values for each variable that are zipped in the proper order) of exmax, eymax, exymax and Nxmax given that all of these variables are some combination of the others.
I have the issue that the type is coming back as a 'finiteset' and it won't let me iterate properly as a result.
import math
import numpy as np
from astropy.table import QTable, Table, Column
from collections import Counter
import operator
from sympy import *
exmax= symbols('exmax')
eymax= symbols('eymax')
exymax= symbols('exymax')
Nxmax=symbols('Nxmax')
Stiffnessofplies=list(1,1) #This isn't the actual value, but it is important to have a len of two #here for later on
Nxmax=[78.4613527541947*exmax + 8.06201746514537e-15*exymax + 4.07395485454472*eymax,
69.4081197440953*exmax + 1.35798495151491*eymax]
exmax= [{(-1.0275144618526e-16*exymax - 0.0519230769230769*eymax,)},
{(-0.0195652173913043*eymax,)}]
eymax = [{(-0.0284210526315789*exmax + 8.11515424209734e-19*exymax,)},
{(-0.299999999999999*exmax,)}]
exymax = [{(-7.78938885521292e-17*exmax + 1.12391245013323e-18*eymax,)}, {(0,)}]
exmax2=[]
for i in emax:
for j in i:
exmax2.append(j)
eymax2=[]
for i in eymax:
for j in i:
eymax2.append(j)
exymax2=[]
for i in exymax:
for j in i:
exymax2.append(j)
I did these last three equations to try and flatten everything out to make it iterable. Here are other things I have tried:
#Pleasework=[]
#for i in range(0,len(Stiffnessofplies)):
# linsolve([exmax2[i]], [eymax2[i]], [exymax2[i]], [Nxmax[i]], (exmax, eymax, exymax,Nxmax))
#System= exmax2[0],eymax2[0],exymax2[0]
#linsolve(System, exmax,eymax,exymax,Nxmax)
#Masterlist=list(zip(exmax,eymax,exymax,Nxmax))
I think one of my main issues is the type I'm getting back 'finiteset' really doesn't work well when trying to iterate the list for both values in the list.
Recently, I was working on a data mining project for school using python, pycharm, and numpy arrays. My goal was to find the covariance matrix without using .cov(). The data set given was about (19,000 x 11). I used a subset of this for testing (12 x 11). While trying to center the data, I wrote a function called def center(self, data): Basically, it's a for loop that takes a column slice (data[:, i]) of the 2-D array and iterates through it assigning to the original value that value minus the mean of the column, (val = val - columnMean) the following is the loop:
for i in range(len(data[0])):
for j in range(len(data[:])):
data[:, i][j] = data[:, i][j] - data[:, i].mean()
I have run this code and dozens of variations of it, literally, hundreds of times, but the assignment never happens. The best I can figure is that I'm not using a conda environment with pycharm. I downloaded anaconda3, but I can't find the conda.exe for the path, however I'm not even sure this is the problem.
These are the imports in the program:
#!/usr/bin/python, import os, import sys, import pandas as pd, import csv, import numpy as np, import random
This is the actually function:
class AssignmentThree:
def __init__(self, file):
self.data = -1
def center(self, data):
d = data
for col in range(len(d[0])):
mean = d[:, col].mean()
for row in range(len(d[:, 0])):
d[row][col] = d[row][col] - mean
# Originally I used d[:, i][row] = d[:, i][row] - mean
This is a sample of the "data" in file "magic04.data":
28.7967,16.0021,2.6449,0.3918,0.1982,27.7004,22.011,-8.2027,40.092,81.8828,g
31.6036,11.7235,2.5185,0.5303,0.3773,26.2722,23.8238,-9.9574,6.3609,205.261,g
162.052,136.031,4.0612,0.0374,0.0187,116.741,-64.858,-45.216,76.96,256.788,g
23.8172,9.5728,2.3385,0.6147,0.3922,27.2107,-6.4633,-7.1513,10.449,116.737,g
75.1362,30.9205,3.1611,0.3168,0.1832,-5.5277,28.5525,21.8393,4.648,356.462,g
51.624,21.1502,2.9085,0.242,0.134,50.8761,43.1887,9.8145,3.613,238.098,g
48.2468,17.3565,3.0332,0.2529,0.1515,8.573,38.0957,10.5868,4.792,219.087,g
it was passed as a terminal parameter using sys and assigned by a separate function as follows:
Afile = open(file)
self.data = pd.read_csv(Afile, header=None, delimiter=',', usecols=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
What I found is that I can assign a variable like "d[:, i] = d[:, i].mean()" without a problem, but:
"d[:, i][row] = d[:, i][row] - d[:, i].mean()" or
"d[row][col] = d[row][col] - mean"
never assigns anything to "d[:, i][row]/ or d[row][col]" and it remains unchanged. To top it off, when I first ran the program the first "d[:, i].mean()" was equal to 0, which explained why the value never changed, however I have run the code with other hard set values and the behavior persist. The code never throws any warnings or other indications of compiler error.
If anyone has some insight it would be greatly appreciated.
This is somehow related to my post get ride of Recursion Error in large number of iteration and access to element of joint of 2 lists iteratively python
I have 2 more questions:
1-How I can write a code to access to [3,3] in list X=[[[[[],[1,1]],[2,2]],[3,3]],[4,4]]
because as I check the size it is (2,) all of them are considered as element 0? and how I can change it to
2-How I can get rid of recursion error of the following code when T is big number?
import numpy as np
import random
def functioncalculatedB():
return([(random.randint(1,2)),(random.randint(1,3)),(random.randint(1,4)),(random.randint(1,5)),random.randint(1,6)])
def main():
'''X=[[[[[],1],2],3],4]
print(np.shape(X))
'''
episodes=40000
T=2000000
for e in range(episodes):
X=[]
for time_t in range(1,T+1):
B= functioncalculatedB() #B=[b0,b1,b2,b3,b4]
X=[X, B] #X.extend(B)
np.save('./save/X.npy',X)
if __name__ == "__main__":
main()
Hi I found in book:Numerical Methods in engineering with Python the module run_kut5, but for that module I need module printSoln, all provided in the book. Now I cp the code, made necessary line adjustments and so. The code looks like:
# -*- coding: cp1250 -*-
## module printSoln
''' printSoln(X,Y,freq).
Prints X and Y returned from the differential
equation solvers using printput frequency ’freq’.
freq = n prints every nth step.
freq = 0 prints initial and final values only.
'''
def printSoln(X,Y,freq):
def printHead(n):
print "\n x ",
for i in range (n):
print " y[",i,"] ",
print
def printLine(x,y,n):
print "%13.4e"% x,f
for i in range (n):
print "%13.4e"% y[i],
print
m = len(Y)
try: n = len(Y[0])
except TypeError: n = 1
if freq == 0: freq = m
printHead(n)
for i in range(0,m,freq):
printLine(X[i],Y[i],n)
if i != m - 1: printLine(X[m - 1],Y[m - 1],n)
Now, when I run the program it says:
line 24, in <module>
m = len(Y)
NameError: name 'Y' is not defined
But I cp'd from the book :\ So now when I call the run_kut module I get the same error, no Y defined in printSoln...
I'm trying to figure this out but I suck :(
Help, please...
I would guess it's a tabs/spaces problem - check that you don't have mixed tabs and spaces in the indentation.
EDIT: If it's not indentation, and since your error message contains "<module>" and not a filename, I'm guessing you're pasting this into an interactive interpreter.
Instead, you should paste the code into a file called printsoln.py, and then run this in the interactive interpreter:
from printsoln import printSoln
If you still want to paste it all in the interpreter then you'll probably need to remove the blank lines - those after def printSoln and after each internal function. The interactive interpreter uses blank lines to figure out when you're done with a multi-line definition, and tries to evaluate m = len(Y) outside the context of function printSoln. In this context, variable Y doesn't exist.