Right now I'm working on making Python "type" on your screen (I was feeling bored and experimental), and I got this far on my own, but I can't find any way to use decimals in my script, as Python only accepts whole numbers for randint().
#include <stdio.h>;
import sys;
import time;
import os;
import random;
os.system("clear");
script = "I just really need to type something right now. I'm not sure why, but I really feel like typing on the Chromebook right now. It seems kinda weird, but I like doing this. It helps me practice what I'm doing. I've noticed that I'm a lot worse at typing lately, and I don't know why. Maybe it's because I've been working with a chunky keyboard, and these Chromebook keyboards are extremely thin. Yup, this is actually entertaining for me. I'm not exactly sure why I want to do this, but I just do. It's almost addicting to me, and I don't know why.\n";
for i in range(0, 587):
sys.stdout.write(str(scripti));
sys.stdout.flush();
time_num = random.randint(0.1, 0.4);
time.sleep(time_num);
The output I get is:
ITraceback (most recent call last):
File "main.py", line 11, in <module>
time_num = random.randint(0.1, 0.4);
File "/usr/lib64/python2.7/random.py", line 242, in randint
return self.randrange(a, b+1)
File "/usr/lib64/python2.7/random.py", line 187, in randrange
raise ValueError, "non-integer arg 1 for randrange()"
ValueError: non-integer arg 1 for randrange()
Any ideas?
EDIT: Don't tell me how to make this simpler, as this was just for learning.
Why don't you use the random uniform distribution instead? In this case you can get non integer number values. Use:
import random
random.uniform(0.1,0.4)
If you have to use randint, you could do time_num = randint(1, 4)/10.
for i in range(0, 587):
... nothing is indented there (unless you didn't post the indents in the question).. so it's practically useless
For the time_num Variable you could cast it like this:
time_num = double(random.randrange(1, 4) \ 10
you must be trying to get it in milliseconds because python uses Seconds for the time import
but you could also rephrase it like instead of using randint use random.randrange(#1, #2)
And I don't know the sys import but you used this -> sys.stdout.write(str(scripti));
BUT your variable is named "script".........
Related
I'm using python scripting for Strand/Straus7 importing his DLL.
I'm trying to call a function for set the units, called St7SetUnits, following the manual (Img.1) and watching the .py scripting of the DLL that I imported (Img.2). The function expected a c_long and a ctypes.POINTER.(c_long), as specify in the script (Img.3)
Here the complete manual strand7.com/downloads/Strand7%20R246%20API%20Manual%20TOC.pdf
and here the .py scripting https://www.dropbox.com/s/88plz2funjqy1vb/St7API.py?dl=0
As specify at the beginning of the manual I have to convert the list in ctypes array (Img.4).
The function I call is the same of the example, but I can't call it correctly.
I write
import St7API as SA
import ctypes
SA.St7Init()
unitsArray = ctypes.c_int * SA.kLastUnit
units = unitsArray()
units[0] = 0
units[1] = 1
units[2] = 3
units[3] = 1
units[4] = 1
units[5] = 2
SA.St7SetUnits(1, units)
But returns error
expected c_long, got c_long_Array_6
If I try something else, for example an int from the array
SA.St7SetUnits(1, units[0])
the error change in
expected LP_c_long, got int
I tried many solution, but no one works.
Can anyone help me?
Thanks a lot
I know its been a while, but this works for me:
units_type=ctypes.c_long*6
Units = units_type(0,1,3,1,1,2)
St7API.St7SetUnits(1,Units)
From your screenshots it looks like you might be using Grasshopper. If so, you might need to explicitly cast the units array to a pointer by adding this line to the top of your script:
PI = ctypes.POINTER(ctypes.c_long)
And do this whenever you pass an array from IronPython to St7API:
SA.St7SetUnits(1, PI(units))
This answer has slightly more.
When I try to learn more about python, I found this page:http://python.jobbole.com/88045/ . Ok,I must say it was wrote by Chinese.
Here is a example:
import random
def func(ok):
if ok:
a = random.random()
else:
import random
a = random.randint(1, 10)
return a
func(True)# UnboundLocalError: local variable 'random' referenced before assignment
The words, referenced before assignment, I could not understand, in my thought, I had import the random at the top.
Through I import random the second time in else, but I had import random before use,is yet?
So, anyone can help me about the UnboundLocalError when I import more than once?
I am new to python, and my English is not good enough, so please point out what I had not explain enough or the words that not polite enough.
Thanks!
I'm trying to generate a random.gauss numbers but I have message error. Here is my code:
import sys,os
import numpy as np
from random import gauss
previous_value1=1018.163072765074389
previous_value2=0.004264112033664
alea_var_n=random.gauss(1,2)
alea_var_tau=random.gauss(1,2)
new_var_n= previous_value1*(1.0+alea_var_n)
new_var_tau=previous_value2*(1.0+alea_var_tau)
print 'new_var_n',new_var_n
print 'new_var_tau',new_var_tau
I got this error:
Traceback (most recent call last):
File "lolo.py", line 15, in <module>
alea_var_n=random.gauss(1,2)
AttributeError: 'builtin_function_or_method' object has no attribute 'gauss'
Someone know what's wrong, I'm a newbye with python. Or is it a numpy version problem.
For a faster option, see Benjamin Bannier's solution (which I gave a +1 to). Your present code that you posted will not work for the following reason: your import statement
from random import gauss
adds gauss to your namespace but not random. You need to do this instead:
alea_var_n = gauss(1, 2)
The error in your post, however, is not the error you should get when you run the code that you have posted above. Instead, you will get the following error:
NameError: name 'random' is not defined
Are you sure you have posted the code that generated that error? Or have you somehow included the wrong error in your post?
Justin Barber shows you an immediate solution for your problem.
Since you are using NumPy you could however use their generators as well since they appear to be significantly faster (about a factor 5-7 on my machine), e.g.
alea_var_n = np.random.normal(1, 2)
I'm fairly new to python and understand that recursion is an important concept to grasp. I've been dabbling with various scripts to exercise my knowledge and have come up with the following script to simulate a lottery draw, where you simply draw six from 49 numbers and compare them with another six to see if you've won. I'm struggling though with the recursive function taking the value of another function.
I'm sure it's going to be straightforwardish, but cannot fathom it myself.
Here's my code so far:
from random import randint
def drawSix():
six = []
while len(six) < 6:
a = randint(1,49)
if a not in six:
six.append(a)
return sorted(six)
def lottery(draw,ticket):
if draw == ticket:
return 'win'
return lottery(drawSix(),drawSix())
I call the function with lottery(drawSix(),drawSix())
and get the following recursively.
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
lottery(drawSix(),drawSix())
File "/Users/johnhopkins/Desktop/lottery.py", line 14, in lottery
return lottery(drawSix(),drawSix())
def lottery(draw,ticket):
if draw == ticket:
return 'win'
return lottery(drawSix(),drawSix())
The odds of you actually generating two identical tickets are quite large, well over 1000 which is the maximum stack size of Python.
You need to either do this iteratively to avoid blowing your stack.
def lottery(draw,ticket):
while draw != ticket:
draw, ticket = drawSix(), drawSix()
return "win"
Note this has a very ugly O(n) of O(inf) you could end up running this forever if you were unlucky and still not finding a winning pair
Well, your question has has been answered, but I would suggest changing your drawSix function. As it is now, it could technically run forever. random has a sample method to generate unique numbers.
def drawSix():
return sorted(random.sample(range(1, 50), 6))
Yes - the lottery function will keep on calling itself, each time putting a new version of itself onto the call stack, going deeper and deeper into itself until there are two matching numbers.
This can take a long time, and Python will eventually say "oi! stop it!" and crash.
Some programming languages have a feature called 'tail call optimisation', which means if you try to return the result of the same function, instead of making a new call to the function inside the current one, it simply replaces itself in the stack.
Python doesn't do that.
def lottery():
while (drawSix() != drawSix()):
continue
return 'win!'
will have the same effect as your recursive version, but won't die with recursion errors.
You have not made any programming mistakes. However, the probility of winning the lottery is very small, so you need to generate a lot. Easy recursion add something to the stack.
Number of lotto tickets can be found by the formula for combinations with repetition:
(49+6-1)! / (6! * (49-1)!) = 25827165
This is a lot... Decrease the number 6 or 49, add some debugging lines and you'll see that the code works fine!
I'm stucked on the chapter 3.3 "Math functions" of "Think Python".
It tells me to import math (through the interpreter).
Then print math and that I should get something like this:
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
Instead I get <module 'math' <built-in>>
Anyway that's not the problem. Though I wasn't able to find a 'math.so' file in my python folder. The most similar file is named test_math.
The problem is that I'm supposed to write this:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
When I write the first line it tells me this:
Traceback <most recent call last>:
File "<stdin>", line 1, in <module>
NameError: name 'signal_power' is not defined
On the book says "The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that signal_power and noise_power are defined)."
So I assume that the problem might be that I didn't defined 'signal_power', but I don't know how to do it and what to assign to it...
This is the first time that I feel that this book is not holding my hand and I'm already lost. To be honest I don't understand this whole chapter.
By the way, I'm using Python2.7 and Windows XP. I may copy and paste the whole chapter if anyone feels that I should do it.
Python is my first language and I already tried to learn it using "Learn Python the hard way" but got stucked on chapter 16. So I decided to use "Think Python" and then go back to "Learn Python the hard way".
You've figured it out - you have to set signal_power's value before using it. As to what you have to set it to - it's not really a Python related question, but 1 is always a safe choice :) While you are at it, don't forget to define noise_power.
You indeed need to assign a value to both signal_power and noise_power. The author likely left them out because the values are arbitrary. Even when supplied with exact values in a text, you should also play around with the values. After all, there's not much point in having you type anything in if the results on the screen are the same as on the page.
signal_power = 100
noise_power = 17
This particular example defines the mathematical relationship between variables. If it were presented as such, it wouldn't be such a mystery that exact values were left out, as they would be supplied by someone when using the formula. The same holds for the code sample.
The book is for an older version of python apparently. But that is unrelated to your actual question.
Try defining signal_power. For example
signal_power = 0
You can't use a variable without defining/declaring it first. When you say ratio = signal_power / noise_power,
you're trying to access two variables that the interpreter has never heard about.
Before telling the machine what to do with the variables, you have to introduce them to it first.
You do this by declaring them:
signal_power = 123
noise_power = 321
You can define them as any number you want, not only 123 and 321, but you must define them before using them.