Or reverse your vector:
import math
p1 = (0.0, 0.0)
p2 = (1.0, 1.0)
# use vector from p2 to p1
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
angle = math.atan2(dy, dx)
angle = math.degrees(angle)
print(angle) # 45.0
Or reverse your vector:
import math
p1 = (0.0, 0.0)
p2 = (1.0, 1.0)
# use vector from p2 to p1
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
angle = math.atan2(dy, dx)
angle = math.degrees(angle)
print(angle) # 45.0
Here is one example:
import pprint as pp
mydic = {
'a123': [1, 2, 2, 4],
'a124': [1, 2, 3, 4],
'a125': [1, 2, 2, 4],
'a126': [1, 2, 4, 5]
}
newdic = {}
val_list = []
for key, val in mydic.items():
if val not in val_list:
newdic[key] = val
val_list.append(val)
pp.pprint(newdic, width=50)
''' output -->
{'a123': [1, 2, 2, 4],
'a124': [1, 2, 3, 4],
'a126': [1, 2, 4, 5]}
'''
The other question is, does your hex string convert back to decimal?
a = 255
hx = hex(a)
print(hx)
print(int(hx, 16))
hx = hex(a)[2:]
print(hx)
print(int(hx, 16))
''' output -->
0xff
255
ff
255
'''
For the use of the IDLE IDE see
http://www.daniweb.com/software-development/python/threads/20774/starting-python#post104834
If you execute python.exe, it comes up with the black console window.
If you execute pythonw.exe, nothing will show. It is used for GUI programs where the black console window would interfere.
Actually, if you use one of the many IDE (like IDLE), to run your code, then you don't have to worry about this.
An egg white omelette with spinach, mushrooms and swiss cheese.
In the California desert it will be a cool 110 deg F (43 deg C) in the shade today.
Iran’s government-controlled telecommunications firm bought US-made surveillance equipment from a Chinese company as part of a $130.6 million deal.
cx_Freeze works with both versions of Python
http://www.blog.pythonlibrary.org/2010/08/12/a-cx_freeze-tutorial-build-a-binary-series/
Sunny. hot, with snow and floods.
Age is an issue of mind over matter. If you don't mind, it doesn't matter.
(MT)
Be careful about reading health books. You may die of a misprint.
~~~ Mark Twain
A person who won't read has no advantage over one who can't read.
~~~ Mark Twain
Snapping turtle is sometimes called snapper.
I use Microsoft's SkyDrive and they give you 7GB free. Works well with the MS file manager.
The Tkinter GUI toolkit's equivalent to raw_input() is the Entry widget. Here is an example:
# simple Tkinter code
# using two labels, an entry and a button
# make tk the name space regardless of Python version
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
def action():
"""
get the entry string
reverse string using slicing [::-1]
show the result
"""
name = enter.get()
label2.config(text=name[::-1])
# create the root window
root = tk.Tk()
root.title("My title")
# create all the widgets
# the prompt label
label1 = tk.Label(root, text='Enter name:', width=30)
# the entry
enter = tk.Entry(root, bg='yellow')
# the action button
button = tk.Button(root, text='Reverse name', command=action)
# the result label
label2 = tk.Label(root, text='')
# pack widgets vertically in the root window in order
label1.pack(side='top')
enter.pack(side='top')
button.pack(side='top')
label2.pack(side='top')
# start cursor in entry
enter.focus()
# start the event loop
root.mainloop()
You exit via the root window upper corner x
Since you are not passing any args, this will do:self.bd4 = Tkinter.Button(self.frame, text="D4", command=self.roll_dice)
also
self.sticky_all = 'ewns'
Look into Python module re
What did you select?
Something like random.choice()?
The reason your instructor is using cs1graphics module is so that outside people can not help you as easily as with common Tkinter GUI toolkit. Most likely your module is limited wrapper of Tkinter.
A number of these Tkinter wrappers have appeared over the years, usually from folks that want to sell you their book. These books are then used by somewhat myopic instructors that are too lazy to teach the full Tkinter code.
Line 11 may give you error if you use Python3,
change to:
print(item)
A somewhat updated version:
''' pyttsx_speech_test102.py
speaks the present time in English, for instance
"Sat Apr 27 15:10:59"
as
"Saturday April 27th 15 hours 10 minutes and 59 seconds"
download
pyttsx-1.1.tar.gz
from
https://pypi.python.org/pypi/pyttsx
also needs
setuptools-0.6c11.win32-py2.7.exe
from
https://pypi.python.org/pypi/setuptools#files
install setuptools first then
unpack the tar file and run (using Python27)
setup.py install
it installs
C:\Python27\Lib\site-packages\pyttsx-1.1-py2.7.egg
info at
https://github.com/parente/pyttsx
and
http://pyttsx.readthedocs.org/en/v1.1/engine.html#examples
tested with Python273 in Windows7 (has the SAPI speech engine installed)
'''
import pyttsx
import time
engine = pyttsx.init()
# speech rate in words per minute
engine.setProperty('rate', 100)
# volume 0.0 to 1.0
engine.setProperty('volume', 0.9)
now_tuple = time.localtime()
#print(now_tuple) # test
# slice off the year
now_str = time.asctime(now_tuple)[:-4]
print(now_str) # test
engine.say(now_str)
engine.runAndWait()
Do what Microsoft does, create a new and improved version.
Unfortunately the two bombers were Muslims, so there will be quite a bit of hatred going around.
C in school.
"Don't Get Me Wrong" by the Pretenders
Polish sausage, Naan bread and pink lemonade.
Luckily Henri and Henry are pronounced the same in America.
Pork ribs, fresh corn and baked beans. One nice mug full of Miller. What a campus party!
Double click on the code to select all of it, then right click selection and pick copy from the dropdown menu.
In Python3 you can specify the end of the print funtion:print("hello", end='\n') # end='\n' is the default
Similar to C++
cout << "hello" << endl;
Try the Python dictionary with name:[age, weight, sex, ... ] pairs.
What type is shellcode?
Koljik can you give us one meaningful reason why you want to use the goto statement?
If you ever have to maintain somebody else's program code, then goto's are one horror.
I don't smoke, but you smokers please keep smoking so my Altria stock can pay the good dividend it does.
Solar cells are picky. If the incoming photon has too little energy, the cell won’t absorb it. If the photon has too much, the excess is wasted as heat. Today's best solar cells have the efficiency of 25%.
Another approach:
''' re_search_replace1.py
replace second 'bad' with 'good'
'''
import re
s = 'bad1234567bad12345678bad123456789'
print(s) # test
m = re.search('bad', s)
# apply slicing
s1 = s[:m.end()]
s2 = s[m.end():]
print(s1) # test
print(s2) # test
s3 = s2.replace('bad', 'good', 1)
print(s3) # test
print(s1+s3)
'''
bad1234567bad12345678bad123456789
bad
1234567bad12345678bad123456789
1234567good12345678bad123456789
bad1234567good12345678bad123456789
'''
You can do it this way:
class starfighter():
strength = 20
pilot = 55
intelli = 40
stamina = 35
print(starfighter.strength) # 20
print(starfighter.intelli) # 40
Also be aware that in Python2 you might get an integer division unless you force a float:
def average(q):
''' cast a float for Python2 '''
return float(sum(q))/len(q)
q = [1, 2, 3, 4]
avg = average(q)
print(avg) # 2.5
entropic310500 you need to show us some of your code!
You also have to do your indentations properly:
class Rectangle(object):
def __init__(self, x, y):
self.x = x
self.y = y
def area(self):
return self.x*self.y
def perimeter(self):
return self.x*2 + self.y*2
def main():
print("Rectangle a:")
a = Rectangle(5, 7)
print("area: %d" % a.area())
print("perimeter: %d" % a.perimeter())
'''
print("")
print("Rectangle b:")
b = Rectangle()
b.width = 10
b.height = 20
print(b.getStats())
'''
if __name__ == "__main__":
main()
Used print() so code will work with Python2 and Python3.
Python packs a lot of power, take a close look at this:
from string import punctuation
from collections import Counter
data = """\
I love the python programming
How love the python programming?
We love the python programming
Do you like python for kids?
I like Hello World Computer Programming for Kids and Other Beginners.
"""
# convert all upper case leeters to lower case
data = data.lower()
print(data) # test
print('-'*70)
# remove punctuation marks like .,!?
data = "".join(c for c in data if c not in punctuation)
print(data) # test
print('-'*70)
# create a list of (word, frequency) tuples
q = [(word, freq) for word, freq in Counter(data.split()).items()]
# show q sorted by word (default is element index 0)
for word, freq in sorted(q):
print("{:12} {}".format(word, freq))
print('-'*20)
# show q sorted by frequency (element index 1)
for word, freq in sorted(q, key=lambda x: x[1]):
print("{:3d} {}".format(freq, word))
Same problem here:
http://www.daniweb.com/software-development/python/threads/451832/i-dont-know-how-to-use-python..-please-help#post1957570
and here:
http://forums.devshed.com/python-programming-11/i-don-t-know-how-to-use-python-help-me-943069.html
and here:
http://forums.devshed.com/python-programming-11/how-do-you-write-a-program-for-this-in-python-943070.html
Sounds like a fun project.
My advice, do not hijack old solved threads, but start your own new thread, it's more polite and people are more willing to help. Give your new thread a meaningful title like "Making a stick figure class".
Give us a hint what OS and Python version you are using. Also the type of GUI toolkit you have decided on. I recommend Tkinter for beginners, it comes with Python.
As far as resizing is concerned look at:
http://www.daniweb.com/software-development/python/code/450373/resize-an-image-from-the-web-pil-tkinter
I assume you are going to use the Python Image Library (PIL). Look at their documentation.
Here is one well commented example:
''' data4_expand.py
data4.csv looks like that:
date,time,v1,v2
03/13/2013,11.23.10,12.3,3.4
03/13/2013,11.23.13,12.7,5.1
03/13/2013,11.23.16,15.1,8.3
03/13/2013,11.23.19,17.8,9.8
03/13/2013,11.23.22,19.6,11.4
03/13/2013,11.23.25,21.3,14.6
03/13/2013,11.23.28,24.2,18.3
'''
# read the csv file and process
with open("data4.csv") as fin:
data_list = []
for ix, line in enumerate(fin):
# strip off trailing new line char
line = line.rstrip()
# split at the separator char
tlist = line.split(',')
date, time, v1, v2 = tlist
# treat title line differently
if ix > 0:
hr, mn, sc = time.split('.')
seconds = float(hr)*3600 + float(mn)*60 + float(sc)
data_list.append([date, time, v1, v2, str(seconds)])
else:
# title line
tlist.append('seconds')
data_list.append(tlist)
# write out the expanded csv file
with open("data5.csv", "w") as fout:
# format data string
data_str = ""
for line in data_list:
print ",".join(line) # test
# use appropriate separator char
data_str += ",".join(line) + '\n'
fout.write(data_str)
print('-'*40)
print("Data file {} has been written".format("data5.csv"))
''' test result >>>
date,time,v1,v2,seconds
03/13/2013,11.23.10,12.3,3.4,40990.0
03/13/2013,11.23.13,12.7,5.1,40993.0
03/13/2013,11.23.16,15.1,8.3,40996.0
03/13/2013,11.23.19,17.8,9.8,40999.0
03/13/2013,11.23.22,19.6,11.4,41002.0
03/13/2013,11.23.25,21.3,14.6,41005.0
03/13/2013,11.23.28,24.2,18.3,41008.0
----------------------------------------
Data file data5.csv has been written
'''
Added few more hints to slate's code:
import urllib2, re
from bs4 import BeautifulSoup
url = 'http://www.indexmundi.com/factbook/regions'
response = urllib2.urlopen(url).read()
soup = BeautifulSoup(response)
row = soup.findAll('li')
# create a dictionary of region:regionname pairs
region_dict = {}
for link in row:
href = link.find('a')['href']
url = "http://www.indexmundi.com"
countryurl = url + href
regionname = link.find('a').text
response = urllib2.urlopen(countryurl).read()
soup = BeautifulSoup(response)
data_table = soup.findAll('td')
for data in data_table:
region = data.find('a').text
#print(regionname, region) # test
# make region upper case
region_dict[region.upper()] = regionname
# tab separated values (country\tarea\tpopulation)
data_line = "BERMUDA\t54\t69080"
data_list = data_line.split('\t')
print(data_list) # ['BERMUDA', '54', '69080']
if data_list[0] in region_dict:
# insert regionname at index 1
data_list.insert(1, region_dict[data_list[0]])
print(data_list) # ['BERMUDA', u'North America', '54', '69080']